Fowad Hamza
Fowad Hamza

Reputation: 113

Accessing qml objects from loaded qml using cpp code

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"
    }
}

Upvotes: 6

Views: 1593

Answers (2)

Milad Karimi
Milad Karimi

Reputation: 31

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");

Upvotes: 0

folibis
folibis

Reputation: 12874

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")

Upvotes: 3

Related Questions