6

I have a main.qml which loads Page1.qml using loaders. How can I find object 'whiteArea' within Page1.qml from my cpp code?

I am currently using the following to fetch an object and would like to obtain the loaded qml as well like this as well.

QObject * object = engine.rootObjects().at(0)->findChild<QObject *>  ("yourObjectName");

main.qml

import QtQuick 2.3
import QtQuick.Controls 1.2
import myplugin 1.0

ApplicationWindow {
    id:app
    visible: true
    width: 640
    height: 480
    title: qsTr(" World")
    objectName: "Appwindow"
    property ApplicationWindow appwindow:app
    Label {
        objectName: "label"
        text: qsTr(" World")
        anchors.centerIn: parent
    }

    MyItemTest{
        objectName: "myItem"
        anchors.fill: parent
    }

    Rectangle{
        objectName: "Rectangle"
        id:rect
        width: 50
        height: 50
        color: "yellow"
    }

    Button {
        objectName: "MyButton"
        id: btnClick
        text : "btn"
        Loader { id: pageLoader }
        onClicked: {
            pageLoader.source = "Page1.qml"

        }
    }
}

Page1.qml

import QtQuick 2.0
import QtQuick 2.3
import QtQuick.Controls 1.2
import myplugin 1.0

Item {
    Rectangle{
        objectName: "whiteArea"
        id:rect
        width: 50
        height: 50
        color: "white"
    }
}

2 Answers 2

3

From the Qt documentation:

The loaded object can be accessed using the item property.

So you should do some subsearch inside a loaded item, for example like this:

QObject * loader = engine.rootObjects().at(0)->findChild<QObject*>("loader");
qWarning() << loader;
QObject * item = qvariant_cast<QObject*>(QQmlProperty::read(loader,"item"));
qWarning() << item;
QObject *whiteArea = item->findChild<QObject *>("whiteArea");
qWarning() << whiteArea;

The output:

QQuickLoader(0x24918240, name = "loader")
QQuickItem(0x24919740)
QQuickRectangle(0x24919728, name = "whiteArea")
Sign up to request clarification or add additional context in comments.

Comments

0

First of all , give Loader an object name property, like "loader". then be sure at the time you running the below code , loader.item is set with"Page1.qml" then do something like this:

QObject* loader = m_engine->rootObjects()[0]->findChild<QObject*>("loader");
QObject* page= qvariant_cast<QObject *>(loader->property("item"));
QObject* whiteArea = page->findChild<QObject*>("whiteArea");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.