When to use what classes in Qt Quick 2 and how?

qml, qt5, qtquick2

Solution

I think you're making confusion about things on different levels, and that acually makes this question a "compound" question which should be split in smaller questions...

Anyhow:

- when you need a `QWindow` which is able to host QtQuick 2 content, then you need a `QQuickView` or a `QQuickWindow` (usually the former, has provides more convenience; see their docs).

- QtQuick2 is not `QGraphicsView`-based. It's not even in QtWidgets -- you can't use any widgets-related class or API there.

- The easiest way to bind a QML element property to the one of a C++ object is just exposing that object to the QML engine, then perform an ordinary binding.

For instance:

class MyObject : public QObject {
    Q_OBJECT
    Q_PROPERTY(int horizontalPos READ horizontalPos NOTIFY horizontalPosChanged)
public:
    int horizontalPos() const { return m_horizontalPos; }
signals:
    void horizontalPosChanged();
    // etc.
}

Then you can expose an instance of MyObject to the QML engine:

MyObject obj;
QQuickView view;
// exposes the object under the "_myObject" name
view.engine()->context()->setContextProperty("_myObject", &obj); 

The underscore is a nice touch to underline the fact that this name comes from the C++ world.

Finally, in QML, you can just bound to the property:

Rectangle {
    x: _myObject.horizontalPos // voilà, they're bound together
}

Problem

I am trying to write a game with Qt 5.1 and Qt Quick 2 and it's new (faster) graphic engine. I have been reading documentation for hours but still can't figure out what classes to use if I want to move items on screen whose positions are determined by C++ code. In QGraphics it was easy: I create an instance of QGraphicsScene add any inheritor of QGraphicsItem to it and then create an instance of QGraphicsView that is a Widget and displays all items and their changes. I connect QGraphicsItem to signals to make changes. In Qt Quick 2 I first read the - official examples that only used QML and Javascript, - then I thought I found the equivalents to QGraphics, namely QDeclarativeEngine, QDeclarativeComponent and QDelcarativeView and was ready to create custom QML elements with Q_PROPERTY - UPDATE: Just now I found out that QDeclarative* is Qt Quick 1 and QQml* is the equivalent Qt Quick 2 prefix. - But then I also found QQuickItem, QQuickWindow, QSGNode etc.. After reading many tutorials documentations I still don't know what the "default" solution is. Every tutorial shows something different. I am overwhelmed with all the examples and classes. - Can someone please give me a basic example that is based on Qt Quick 2 and where images on a canvas are moved around by signals that are being sent from regular QObjects written in C++? - Can you please help me categorize all the classes I mentioned. Which do I use when?

Original source