首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QStateMachine的同步问题

QStateMachine的同步问题
EN

Stack Overflow用户
提问于 2015-08-13 01:53:02
回答 2查看 363关注 0票数 2

我的程序中有一个QStateMachine的实例。我在它的构造函数中配置它的状态、转换和初始状态。当然,我在构造函数中启动它。

代码语言:javascript
复制
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被发出。

代码语言:javascript
复制
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...

如何确保机器在构造时处于初始状态?

EN

回答 2

Stack Overflow用户

发布于 2015-08-13 02:16:41

状态机是异步的,由事件循环驱动。您没有理由在启动时使用该信号将机器移动到另一个状态。现在,您希望在启动时以及在发出foo时从stateA转换到stateB

  1. 记住,连接的目标可以是信号,也可以是插槽。您可以将状态机的started信号连接到foo信号。这样,foo将在机器启动并处于初始状态时发出。
  2. 如果您不关心foo信号,您可以将转换设置为直接在机器的started信号上触发。
  3. 如果您始终希望从stateA转换到stateB,即使在计算机启动后一段时间,并且以某种方式重新进入stateA,您也可以添加从初始状态到stateB的无条件转换。机器一旦进入stateA,就会离开它,然后进入stateB,automatically.

从最后一个开始检查解决方案,如果需要不太通用的解决方案,则向上移动。

票数 0
EN

Stack Overflow用户

发布于 2015-08-13 03:08:12

您可以通过在构造函数中创建一个事件循环来确保机器在构造时处于初始状态:

代码语言:javascript
复制
// ...
this->start();
QEventLoop* eventLoop = new QEventLoop(this);
QObject::connect(
    this, &Machine::started,
    eventLoop, &QEventLoop::quit
);
eventLoop->exec();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31972167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档