main.cpp Example File
statemachine/pingpong/main.cpp
#include <QtCore>
#include <stdio.h>
class PingEvent : public QEvent
{
public:
PingEvent() : QEvent(QEvent::Type(QEvent::User+2))
{}
};
class PongEvent : public QEvent
{
public:
PongEvent() : QEvent(QEvent::Type(QEvent::User+3))
{}
};
class Pinger : public QState
{
public:
Pinger(QState *parent)
: QState(parent) {}
protected:
void onEntry(QEvent *) override
{
machine()->postEvent(new PingEvent());
fprintf(stdout, "ping?\n");
}
};
class PongTransition : public QAbstractTransition
{
public:
PongTransition() {}
protected:
bool eventTest(QEvent *e) override {
return (e->type() == QEvent::User+3);
}
void onTransition(QEvent *) override
{
machine()->postDelayedEvent(new PingEvent(), 500);
fprintf(stdout, "ping?\n");
}
};
class PingTransition : public QAbstractTransition
{
public:
PingTransition() {}
protected:
bool eventTest(QEvent *e) override {
return (e->type() == QEvent::User+2);
}
void onTransition(QEvent *) override
{
machine()->postDelayedEvent(new PongEvent(), 500);
fprintf(stdout, "pong!\n");
}
};
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QStateMachine machine;
QState *group = new QState(QState::ParallelStates);
group->setObjectName("group");
Pinger *pinger = new Pinger(group);
pinger->setObjectName("pinger");
pinger->addTransition(new PongTransition());
QState *ponger = new QState(group);
ponger->setObjectName("ponger");
ponger->addTransition(new PingTransition());
machine.addState(group);
machine.setInitialState(group);
machine.start();
return app.exec();
}