Itay Grudev
Itay Grudev

Reputation: 7426

How do I interact with QML from C++ in QtQuick 2.0

Let’s say that we have a very simple QML file, like this one:

import QtQuick 2.0

Rectangle {
    width: 800
    height: 600
    color: '#000'

    Text {
        text: qsTr("Hi all")
        anchors.centerIn: parent
    }
}

The QML File is loaded with the QtQuick2ApplicationViewer helper class, like this:

QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/MyApp/Login/Window.qml"));
viewer.showFullScreen();

How should I proceed, if for example I would like to change the Rectangle’s color to white, from C++. My guess was:

QQuickItem *window = viewer.rootObject();
window->setProperty("color", "#fff");

But all that does is the following compiler error:

invalid use of incomplete type 'struct QQuickItem'
forward declaration of 'struct QQuickItem'

Upvotes: 1

Views: 3254

Answers (2)

guest
guest

Reputation: 21

QObject *rootObject = (QObject *)viewer.rootObject();
rootObject->setProperty("color", "red");

Upvotes: 2

Luca Carlon
Luca Carlon

Reputation: 9976

Then QQuickItem was forward declared somewhere in a header you included, but not fully qualified. Here more information.

Upvotes: 6

Related Questions