Question

I am building a program with a largely sequential flow but also some alternative paths. I thought that a state machine might be the simplest way of implementing this since Qt provides such a class: QStateMachine (also see API).

However, I seem to have quite a number of states (20+). Also, I have a number of different transition events (let's say buttons 1-10). So e.g. pressing button x would cause a transition of state 13 to 14.

Entering or leaving each state should be able to execute specific functions with parameters, and while each state emits such signals, it is not possible to pass parameters, so that it requires a potentially large number of paramter-less functions.

Reimplementing QAbstractState also seems tedious for this matter, unless it would have methods similar to assignProperty() which allows setting QObject properties on "state-entry".

Is QSignalMapper along with several Signal-Slot-Connections for each state's transition signals to handle multiple actions an appropriate approach?

Was it helpful?

Solution

If you're using C++11, you can connect directly to a lambda that then invokes your function with a specified parameter.

Otherwise, figure out what object is the sender() of your signal, and set a dynamic property on that object. That property can be queried in the slot, and passed on to the function as a parameter.

For example (within a class):

void setup() {
  QState *s2 = new QState();
  s2->assignProperty(myLabel, "text", "state two");
  s2->setProperty("prop", 0);
  connect(s2, SIGNAL(entered()), io, SLOT(testSlot()));
}
Q_SLOT void testSlot() {
  QObject *obj = this->sender();
  QVariant prop = obj->property("prop");
  qDebug() << __FUNCTION__ << prop.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top