2

I'm new to Qt Quck and Qt5/PyQt, and now I've faced a strange problem. I'm trying to find an object with objectName "test" in the below QML definition like this:

self.rootObject().findChild(QObject, "test")

But the call returns None. However, if I move the objectName: "test" property to the parent Tab element, then it's found successfully. It's only not found whem inside the child Item. Similarly, addChannel, modifyChannel and removeChannel objects are also not found by findChild().

import QtQuick 2.0
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.1
import "TouchStyles"

Item {
    ListModel { }

    TouchButtonFlatStyle { id: touchButtonFlat }
    TouchTabViewStyle { id: touchTabView }

    Rectangle {
        width: 480
        height: 230

        TabView {
            currentIndex: 0
            tabPosition: 1
            anchors.fill: parent
            style: touchTabView

            Tab {
                title: "Play"

                Item {
                    anchors.fill: parent
                    PianoKeyboard { anchors.centerIn: parent }
                }
            }
            Tab {
                title: "Channels"
                Item {
                    objectName: "test"
                    ListView {
                        anchors.fill: parent
                        model: listModel
                        delegate: Channel {}
                    }
                    BorderImage {
                        border.bottom: 8
                        anchors.bottom: parent.bottom
                        source: "images/toolbar.png"
                        width: parent.width
                        height: 50

                        RowLayout {
                            anchors.verticalCenter: parent.verticalCenter
                            anchors.horizontalCenter: parent.horizontalCenter

                            Button { text: "Add"; objectName: "addChannel" }
                            Button { text: "Modify"; objectName: "modifyChannel" }
                            Button { text: "Remove"; objectName: "removeChannel" }
                        }
                    }
                }
            }
        }
    }
}

What am I doing wrong? The Qt documentation says that the search is performed recursively. Why doesn't it traverse the entire object tree?

4

1 回答 1

4

问题与选项卡仅在需要时“实例化”这一事实有关。第一个选项卡总是被实例化,所以如果你把它放在objectName那里就会被发现。

仅当您实例化第二个选项卡(选择它)时,它才会在第二个选项卡中找到。同样,使用findChildonTabView可能会实例化每个选项卡(因为它正在寻找它们),因此findChild即使未选择第二个选项卡也可以使用。

结论:首先实例化所有选项卡(在其中执行 afindChildTabView一种方法,但可能是一种 hack),然后findChild为该项目执行。

于 2014-03-11T03:21:17.693 回答