Move Blocks Example

The example animates the blue blocks that you can see in the image above. The animation moves the blocks between four preset positions.

The example consists of the following classes:

  • StateSwitcher inherits QState and can add StateSwitchTransitions to other states. When entered, it will randomly transition to one of these states.
  • StateSwitchTransition is a custom transition that triggers on StateSwitchEvents.
  • StateSwitchEvent is a QEvent that triggers StateSwitchTransitions.
  • QGraphicsRectWidget is a QGraphicsWidget that simply paints its background in a solid blue color.

The blocks are instances of QGraphicsRectWidget and are animated in a QGraphicsScene. We do this by building a state graph, which we insert animations into. The graph is then executed in a QStateMachine. All this is done in main(). Let's look at the main() function first.

The main() Function

After QApplication has been initialized, we set up the QGraphicsScene with its QGraphicsRectWidgets.

    QGraphicsRectWidget *button1 = new QGraphicsRectWidget;
    QGraphicsRectWidget *button2 = new QGraphicsRectWidget;
    QGraphicsRectWidget *button3 = new QGraphicsRectWidget;
    QGraphicsRectWidget *button4 = new QGraphicsRectWidget;
    QGraphicsScene scene(0, 0, 300, 300);

After adding the scene to a QGraphicsView, it is time to build the state graph. Let's first look at a statechart of what we are trying to build.

Note that the group has seven sub states, but we have only included three of them in the diagram. The code that builds this graph will be examined line-by-line, and will show how the graph works. First off, we construct the group state:

    QStateMachine machine;

    QState *group = new QState();
    QTimer timer;
    QObject::connect(group, SIGNAL(entered()), &timer, SLOT(start()));

The timer is used to add a delay between each time the blocks are moved. The timer is started when group is entered. As we will see later, group has a transition back to the StateSwitcher when the timer times out. group is the initial state in the machine, so an animation will be scheduled when the example is started.

    QState *state1;
    QState *state2;
    QState *state3;
    QState *state4;
    QState *state5;
    QState *state6;
    QState *state7;

    state1 = createGeometryState(button1, QRect(100, 0, 50, 50),
                                 button2, QRect(150, 0, 50, 50),
                                 button3, QRect(200, 0, 50, 50),
                                 button4, QRect(250, 0, 50, 50),
    state7 = createGeometryState(button1, QRect(0, 0, 50, 50),
                                 button2, QRect(250, 0, 50, 50),
                                 button3, QRect(0, 250, 50, 50),
                                 button4, QRect(250, 250, 50, 50),

createGeometryState() returns a QState that will set the geometry of our items upon entry. It also assigns group as the parent of this state.

A QPropertyAnimation inserted into a transition will use the values assigned to a QState (with QState::assignProperty()), i.e., the animation will interpolate between the current values of the properties and the values in the target state. We add animated transitions to the state graph later.

    QParallelAnimationGroup animationGroup;
    QSequentialAnimationGroup *subGroup;

    QPropertyAnimation *anim = new QPropertyAnimation(button4, "geometry");

We move the items in parallel. Each item is added to animationGroup, which is the animation that is inserted into the transitions.

    subGroup = new QSequentialAnimationGroup(&animationGroup);
    anim = new QPropertyAnimation(button3, "geometry");

The sequential animation group, subGroup, helps us insert a delay between the animation of each item.

    StateSwitcher *stateSwitcher = new StateSwitcher(&machine);
    group->addTransition(&timer, SIGNAL(timeout()), stateSwitcher);
    stateSwitcher->addState(state1, &animationGroup);
    stateSwitcher->addState(state2, &animationGroup);
    stateSwitcher->addState(state7, &animationGroup);

A StateSwitchTransition is added to the state switcher in StateSwitcher::addState(). We also add the animation in this function. Since QPropertyAnimation uses the values from the states, we can insert the same QPropertyAnimation instance in all StateSwitchTransitions.

As mentioned previously, we add a transition to the state switcher that triggers when the timer times out.


Finally, we can create the state machine, add our initial state, and start execution of the state graph.

The createGeometryState() Function

In createGeometryState(), we set up the geometry for each graphics item.

QState *createGeometryState(QObject *w1, const QRect &rect1,
                            QObject *w2, const QRect &rect2,
                            QObject *w3, const QRect &rect3,
                            QObject *w4, const QRect &rect4,
                            QState *parent)
    QState *result = new QState(parent);
    result->assignProperty(w1, "geometry", rect1);
    result->assignProperty(w2, "geometry", rect2);
    result->assignProperty(w3, "geometry", rect3);
    result->assignProperty(w4, "geometry", rect4);

    return result;

As mentioned before, QAbstractTransition will set up an animation added with addAnimation() using property values set with assignProperty().

The StateSwitcher Class

StateSwitcher has state switch transitions to each QStates we created with createGeometryState(). Its job is to transition to one of these states at random when it is entered.

All functions in StateSwitcher are inlined. We'll step through its definition.

class StateSwitcher : public QState
    StateSwitcher(QStateMachine *machine)
        : QState(machine), m_stateCount(0), m_lastIndex(0)
    { }

StateSwitcher is a state designed for a particular purpose and will always be a top-level state. We use m_stateCount to keep track of how many states we are managing, and m_lastIndex to remember which state was the last state to which we transitioned.

    void onEntry(QEvent *) override
        int n;
        while ((n = (qrand() % m_stateCount + 1)) == m_lastIndex)
        { }
        m_lastIndex = n;
        machine()->postEvent(new StateSwitchEvent(n));
    void onExit(QEvent *) override {}

We select the next state we are going to transition to, and post a StateSwitchEvent, which we know will trigger the StateSwitchTransition to the selected state.

    void addState(QState *state, QAbstractAnimation *animation) {
        StateSwitchTransition *trans = new StateSwitchTransition(++m_stateCount);

This is where the magic happens. We assign a number to each state added. This number is given to both a StateSwitchTransition and to StateSwitchEvents. As we have seen, state switch events will trigger a transition with the same number.

The StateSwitchTransition Class

StateSwitchTransition inherits QAbstractTransition and triggers on StateSwitchEvents. It contains only inline functions, so let's take a look at its eventTest() function, which is the only function that we define..

    bool eventTest(QEvent *event) override
        return (event->type() == QEvent::Type(StateSwitchEvent::StateSwitchType))
            && (static_cast<StateSwitchEvent *>(event)->rand() == m_rand);

eventTest is called by QStateMachine when it checks whether a transition should be triggered--a return value of true means that it will. We simply check if our assigned number is equal to the event's number (in which case we fire away).

The StateSwitchEvent Class

StateSwitchEvent inherits QEvent, and holds a number that has been assigned to a state and state switch transition by StateSwitcher. We have already seen how it is used to trigger StateSwitchTransitions in StateSwitcher.

class StateSwitchEvent: public QEvent
        : QEvent(Type(StateSwitchType))

    explicit StateSwitchEvent(int rand)
        : QEvent(Type(StateSwitchType)),

    enum { StateSwitchType = QEvent::User + 256 };

    int rand() const { return m_rand; }

    int m_rand;

We only have inlined functions in this class, so a look at its definition will do.

The QGraphicsRectWidget Class

QGraphicsRectWidget inherits QGraphicsWidget and simply paints its rect() blue. We inline paintEvent(), which is the only function we define. Here is the QGraphicsRectWidget class definition:

class QGraphicsRectWidget : public QGraphicsWidget
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *,
               QWidget *) override
        painter->fillRect(rect(), Qt::blue);

Moving On

The technique shown in this example works equally well for all QPropertyAnimations. As long as the value to be animated is a Qt property, you can insert an animation of it into a state graph.

QState::addAnimation() takes a QAbstractAnimation, so any type of animation can be inserted into the graph.


© 2017 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.