1

Trying to get this to work in Qt version 5.9

It seems that whenever I create an object within a QML Tab it is unrecognizable by the parent object (or any of the parent's parents, and so on). How do I get the parent objects to recognize the object in the Tab? Or, if impossible, then what is a work-around to call the function of the object within the Tab?

I've boiled down the code to this simplified example:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    Rectangle {
        id: myFunctionCaller

        Component.onCompleted: {
            myParent.myFunction();
            myChild.myFunction();
            myGrandChild.myFunction();
        }
    }

    TabView {
        id: myParent
        property Rectangle grandchild: myGrandChild
        onGrandchildChanged: console.log("Parent recognizes GrandChild");

        function myFunction() {
            console.log("I'm the Parent");
        }

        Tab{
            id: myChild
            property Rectangle grandchild: myGrandChild
            onGrandchildChanged: console.log("Child recognizes GrandChild");

            function myFunction() {
                console.log("I'm the Child");
            }

            Rectangle {
                id: myGrandChild
                function myFunction() {
                    console.log("I'm the GrandChild");
                }
            }
        }
    }
}

I expect this output:

I'm the Parent
I'm the Child
I'm the GrandChild
Parent recognizes Grandchild
Child recognizes Grandchild

However, I get this output:

I'm the Parent
I'm the Child
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.
ReferenceError: myGrandChild is not defined.

The error occurs on these lines:

myGrandChild.myFunction();
onGrandchildChanged: console.log("Parent recognizes GrandChild");
onGrandchildChanged: console.log("Child recognizes GrandChild");
4

1 回答 1

1

Tab是 的子类Loader,因此在变为活动状态Rectangle之前不会创建。Tab

标签被延迟加载;只有已变为当前的选项卡(例如,通过单击它们)才会有有效的内容。您可以通过将 active 属性设置为true来强制加载选项卡

因此,id: myGrandChild仅在加载器中自动创建的(源)组件中可用。

解决方案是,激活选项卡并使用myChild.item

(未测试)

于 2019-05-28T15:53:20.750 回答