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
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:
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).QGraphicsView
-based. It's not even in QtWidgets -- you can't use any widgets-related class or API there.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
}
You could dynamically instantiate custom qml components from the c++ side and modify the properties, still from the C++ side.
You could also just work on some C++ list/model/multiple qobjects containing the positions of your sprites/characters/whatever you display on the screen, and then bind this list with your qml side.
You could also write some QQuickItem from C++ that layouts its children (like proposed here: http://qt-project.org/forums/viewthread/29407/)
-
And here are some links completing peppe's answer / detailing how to mix QtQuick2 & C++ :
The doc pages for Qt Quick 2 / C++ integration (the Qt5 doc isn't well indexed by Google):
The blog post explaining QWidget::createWindowContainer (it's only if you want to embed QtQuick2 in a QtWidget application... otherwise, you can just use the skeleton for a QtQuick2 application from QtCreator):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With