我的程序中有一个QStateMachine的实例。我在它的构造函数中配置它的状态、转换和初始状态。当然,我在构造函数中启动它。
this->stateA = new StateA(this);
this->stateB = new StateB(this);
this->stateA->addTransition(this, &Machine::foo, this->stateB);
this->setInitialState(this->stateA);
this->start();
// At this point the machine is still not in the stateA我面临的问题是,在start()完成执行之前,机器不会移动到初始状态。这导致了一个问题,即在进入初始状态之前,应该将机器从初始状态移动到另一个状态的信号foo被发出。
Machine* machine = new Machine();
// start() was already called here but the machine is still not in the initial state
machine->foo();
// Signal is emitted here (It also may not be emitted. This is not an unconditional transition). But the machine is still not in the initial state and the transition does not happen.
// ...
// Here the machine enters the initial state...如何确保机器在构造时处于初始状态?
发布于 2015-08-13 02:16:41
状态机是异步的,由事件循环驱动。您没有理由在启动时使用该信号将机器移动到另一个状态。现在,您希望在启动时以及在发出foo时从stateA转换到stateB。
started信号连接到foo信号。这样,foo将在机器启动并处于初始状态时发出。foo信号,您可以将转换设置为直接在机器的started信号上触发。stateA转换到stateB,即使在计算机启动后一段时间,并且以某种方式重新进入stateA,您也可以添加从初始状态到stateB的无条件转换。机器一旦进入stateA,就会离开它,然后进入stateB,automatically.从最后一个开始检查解决方案,如果需要不太通用的解决方案,则向上移动。
发布于 2015-08-13 03:08:12
您可以通过在构造函数中创建一个事件循环来确保机器在构造时处于初始状态:
// ...
this->start();
QEventLoop* eventLoop = new QEventLoop(this);
QObject::connect(
this, &Machine::started,
eventLoop, &QEventLoop::quit
);
eventLoop->exec();https://stackoverflow.com/questions/31972167
复制相似问题