C ++ Qt:检查QStateMachine的当前状态

时间:2011-12-15 12:08:22

标签: c++ qt qstatemachine

我正在尝试在Qt(C ++)中实现状态机。 如何检查QStateMachine的当前状态? 我在文档中找不到方法。

THX

4 个答案:

答案 0 :(得分:14)

你试过QStateMachine::configuration()吗?

参考http://www.qtcentre.org/threads/42085-How-to-get-the-current-state-of-QStateMachine

摘自以上网址:

// QStateMachine::configuration() gives you the current states.

while(stateMachine->configuration().contains(s2))
{
     //do something
}

答案 1 :(得分:7)

您可以将属性分配给QStateMachine本身。

// QState        m_State1;
// QState        m_State2;
// QStateMachine m_Machine;

m_State1.assignProperty(m_Label,    "visible", false);
m_State1.assignProperty(&m_Machine, "state",   1);

m_State2.assignProperty(m_Label,     "visible", true);
m_State2.assignProperty(&m_Machine,  "state",   2);

然后,可以从动态属性中读取当前状态。

qDebug() << m_Machine.property("state");

答案 2 :(得分:1)

来自Qt 5.7 Documentation

QSet QStateMachine :: configuration()const

返回此状态机当前所处的最大一致状态集(包括并行状态和最终状态)。如果状态s在配置中,则s的父节点也始终在C。但请注意,机器本身不是配置的明确成员。

使用示例:

bool IsInState(QStateMachine& aMachine, QAbstractState* aState) const
{
   if (aMachine_.configuration().contains(aState)) return true;
   return false
}

答案 3 :(得分:0)

I realize I'm coming in late, but hopefully this answer helps anyone else who stumbles across this.

You mentioned above that you already tried to use configuration(), but none of your states were there--this is because start() is asynchronous.

So, assuming you called configuration() immediately after calling start(), it makes sense that your states weren't there yet. You can get the functionality you want by using the started() signal of the QStateMachine class. Check it out:

stateMachine->setInitialState(someState);
stateMachine->start();
connect(stateMachine, SIGNAL(started()), this, SLOT(ReceiveStateMachineStarted()));

Then, for your ReceiveStateMachineStarted() slot, you could do something like this:

void MyClass::ReceiveStateMachineStarted() {
    QSet<QAbstractState*> stateSet = stateMachine->configuration();
    qDebug() << stateSet;
}

When your state machine enters its initial state, it will emit the start() signal. The slot you've written will hear that and print the config. For more on this, see the following Qt documentation:

http://doc.qt.io/qt-5/qstatemachine.html#started