user8024280
user8024280

Reputation:

Interaction with qml objects from C++ code

I am trying to interact with an qml object from C++ file using QtQuick. But unfortunatelly unsuccessfully for now. Any idea what Im doing wrong? I tried 2 ways how to do it, result of the first was that findChild() returned nullptr, and in second try I am getting Qml comnponent is not ready error. What is the proper way to do it?

main:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    // 1-st attempt how to do it - Nothing Found
    QObject *object = engine.rootObjects()[0];
    QObject *mrect = object->findChild<QObject*>("mrect");
    if (mrect)
        qDebug("found");
    else
        qDebug("Nothing found");
    //2-nd attempt - QQmlComponent: Component is not ready
    QQmlComponent component(&engine, "Page1Form.ui.qml");
    QObject *object2 = component.create();
    qDebug() << "Property value:" << QQmlProperty::read(object, "mwidth").toInt();

    return app.exec();
}

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480

        Page1 {
        }

        Page {
        }
    }
}

Page1.qml:

import QtQuick 2.7

Page1Form {
...
}

Page1.Form.ui.qml

import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

Item {
    property alias mrect: mrect
    property alias mwidth: mrect.width

    Rectangle
    {
        id: mrect
        x: 10
        y: 20
        height: 10
        width: 10
    }
}

Upvotes: 0

Views: 1443

Answers (1)

Pavan Chandaka
Pavan Chandaka

Reputation: 12731

findChild takes object name as first parameter. But not ID.

http://doc.qt.io/qt-5/qobject.html#findChild.

Here in your code, you are trying to query with id mrect. So it may not work.

Add objectName in your QML and then try accessing with findChild using object name.

Something like below (I did not try it. So chances of compile time errors):

Add objectName in QML

Rectangle
{
    id: mrect
    objectName: "mRectangle"
    x: 10
    y: 20
    height: 10
    width: 10
}

And then your findChild as shown below

QObject *mrect = object->findChild<QObject*>("mRectangle");

Upvotes: 5

Related Questions