简体   繁体   中英

QML: modifying a property of a Child object that is defined in a different QML file (not main.qml)

Basically, I have something like:

Main.qml:

ApplicationWindow{
width: 500
height: 500

    Page{
    id: page0

        DataPage{
          id: datapage0  
        }
    }
}

DataPage.qml:

Page{
id: displayPage

    DataDisplay{
    id: dataShow
    }
}

DataDisplay.qml:

Label{
text: "data: "
}

TextArea{
id: dataArea
text: ""
}

I've removed the stuff I think isn't relevant (such as anchors, height, width, etc.). Now, in main.qml, I have a signal coming from the c++ backend:

Connections{
target: modb
onPostData: {
    page0.datapage0.dataShow.dataArea.text = string;
}

And I get the following error: TypeError: Cannot read property 'dataArea' of undefined

So, I wanted to ask: how do I connect that signal to the child object that is defined in DataDisplay.qml? I'm able to get info into main.qml using signals, but seem to be unable to dereference child objects

Edit:

main.cpp:

QQmlContext* ctx0 = engine.rootContext();
ctx0->setContextProperty("ark", &ark);

QQmlContext* ctx1 = engine.rootContext();
ctx1->setContextProperty("comm", ark.comm);

QQmlContext* ctx2 = engine.rootContext();
ctx2->setContextProperty("modb", ark.modb);

is how I set the Context (of 3 classes, as you can see). I'm able to get signals from any of the three into main.qml, as well as call slots in any of the three in main.qml; I haven't yet tried to call slots from the c++ classes in the other qml files, but I assume it would work because I can access the parent's properties from the child

1 - you have 3 pointers pointing to the same object. One is enough. Really!

2 - as long as ark is properly implemented, you can access ark.comm and ark.modb from QML, no need to expose them individually.

3 - you don't seem to understand the scope of id s. Take a look at this exhaustive answer . dataShow is simply not visible from wherever you made the connection.

4 - context properties are not very efficient, that's more of a "quick and dirty" approach to expose C++ to qml. For optimal performance consider a more efficient approach .

All in all, you exhibit the typical symptoms of "getting ahead of yourself". Take the time to learn before you practice.

As you indeed assume you can use the modb variable in the other qml's as well, since it is added to the rootContext . I would advise this option.

Another option you could try is just using dataArea.text = string since the id's go all over the place (it's javascript after all), you should use strong id's in this case.

Another option is to define property alias 's to pass the string through over the objects ( See Qt docs ). Or use property string , but that's even more work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM