我在使用Qt 状态机时遇到了一些问题。我永远无法执行状态:我遇到各种类型的错误,我无法弄清楚问题所在。有关错误和导致错误的代码的更多信息,请参阅下文。
这是我的主要功能:
int main(int argc, char *argv[])
{
// Initialize the app
// ... app initialization here
QApplication app(argc, argv);
// Create the state machine
QStateMachine machine;
MyState* ms1 = new MyState("ms1");
MyState* ms2 = new MyState("ms2");
QFinalState* fs = new QFinalState();
ms1->addTransition(ms2);
ms2->addTransition(fs);
machine.addState(ms1);
machine.addState(ms2);
machine.addState(fs);
machine.setInitialState(ms1);
QObject::connect(&machine, SIGNAL(finished()), new Finisher(), SLOT(OnFinished()));
machine.start();
return app.exec();
}
我在 中设置了断点MyState
,但断点永远不会被击中并且start
/stop
方法永远不会执行(我实际上只希望start
被调用)。应用程序直接进入Finisher::OnFinished
方法。
这是我的状态类:
class MyState: public QState
{
Q_OBJECT
private:
QString _stateName;
public:
MyState(QString stateName, QState * parent = 0):QState(parent), _stateName(stateName){}
~MyState(){}
public slots:
void start()
{
qDebug() << _stateName << " start.";
emit finished();
}
void stop()
{
qDebug() << _stateName << " stop.";
}
signals:
void finished();
//void exited();
};
Finisher 非常简单:
class Finisher:public QObject
{
Q_OBJECT
public slots:
void OnFinished()
{
qDebug() << "Finished!";
QTimer::singleShot(0, QApplication::instance(), SLOT(quit()));
}
};
我尝试了几件事,包括直接设置每个状态的父级:
// If I use the following code, I get an error
// stating that "the state has already been added to this machine"
MyState* ms1 = new MyState("ms1");
MyState* ms2 = new MyState("ms2", ms1);
QFinalState* fs = new QFinalState(ms2);
ms1->addTransition(ms2);
ms2->addTransition(fs);
machine.addState(ms1);
machine.addState(ms2);
machine.addState(fs);
machine.setInitialState(ms1);
// .. and so on
但是,当我似乎无法在machine.addState
调用时添加状态时:
QStateMachine::addState: state has already been added to this machine
QStateMachine::addState: state has already been added to this machine
Unrecoverable error detected in running state machine: Missing initial state in
compound state ''
我也试过只离开构造函数而不调用machine.addState
:
QStateMachine machine;
MyState* ms1 = new MyState("ms1");
MyState* ms2 = new MyState("ms2", ms1);
QFinalState* fs = new QFinalState(ms2);
ms1->addTransition(ms2);
ms2->addTransition(fs);
machine.setInitialState(ms1);
// .. and so on
但是,在这种情况下,我收到以下错误:
QState::setInitialState: state 0xa05e5e0 is not a child of this state (0x43fe94)
QStateMachine::start: No initial state set for machine. Refusing to start.
最后一个很奇怪,因为我明确声明了初始状态ms1
,然后我调用start
了,所以我不知道那里有什么问题。有人对如何让这个例子起作用有任何想法吗?