How can I access my Window object properties from C++ while using QQmlApplicationEngine?

Turning my comment into a proper answer: this is usually done by two methods:

  • Get the root object of your QML scene through a view if you use QQuickView or just the QQmlApplicationEngine directly.

  • This next step can be omitted for root objects, but for “qml objects” in general, you will need to have the objectName property set and then you can find any children with the following method:

QList QObject::findChildren(const QString & name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively) const

C++ side

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDebug>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    // Step 1: get access to the root object
    QObject *rootObject = engine.rootObjects().first();
    QObject *qmlObject = rootObject->findChild<QObject*>("mainWindow");

    // Step 2a: set or get the desired property value for the root object
    rootObject->setProperty("visible", true);
    qDebug() << rootObject->property("visible");

    // Step 2b: set or get the desired property value for any qml object
    qmlObject->setProperty("visible", true);
    qDebug() << qmlObject->property("visible");

    return app.exec();
}

See the documentation for property set and get in the official documentation:

bool QObject::setProperty(const char * name, const QVariant & value)

and

QVariant QObject::property(const char * name) const

Good, we are now more or less done on the C++ side.

QML Side

You will also need to have the objectName property of your qml objects set if you wish to access more than just the root item as follows:

import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    id: mainWindow
    objectName: "mainWindow"
    ...
}

This can be similarly done for any QML object. The key is “objectName” in here. You could omit that for the root object as the C++ side gets the root object directly, but since you are referring to QML objects in your question, I assume that you would like to solve it in general. Once you wish to do the same for any QML object, i.e. including children, you will need to use the objectName property.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)