【问题标题】:findChild returns NonefindChild 返回无
【发布时间】:2018-08-11 05:59:30
【问题描述】:

我看到其他人问这个问题,但我尝试过的都没有奏效。 我正在使用 PyQt 5.10.1。

这里是python代码:

app = QGuiApplication(sys.argv)
view = QQuickView()
view.setSource(QUrl("module/Layout.qml"))
print(view.rootContext())
print(view.findChild(QObject, 'launcherComponent'))
import pdb; pdb.set_trace()
sys.exit(app.exec())

这是 QML 代码:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Window 2.2

import "calendar/resources" as CalendarComponent
import "weather/resources"  as WeatherComponent
import "launcher/resources" as LauncherComponent

import Test 1.0
import Weather 1.0
import Calendar 1.0
import Launcher 1.0


ApplicationWindow {
    id: appId
    width: Screen.desktopAvailableWidth
    height: Screen.desktopAvailableHeight
    visible: true
    modality: Qt.ApplicationModal
    flags: Qt.Dialog
    title: qsTr("NarcisseOS")
    color: "black"

    LauncherComponent.LauncherComponent {
        id: launcherComponentId
        objectName: launcherComponent
        height: parent.height
        width: parent.width
        anchors.centerIn: parent
    }
}

我想尽了一切办法。但是这个 findChild 函数只返回 None。

我尝试重新安装 PyQt5。我试图将 objectName 属性放在一个 Rectangle 对象中,我想也许一个更通用的对象会起作用。一个都没用。

【问题讨论】:

    标签: python pyqt qml pyqt5


    【解决方案1】:

    您的代码有几个错误:

    • objectName 属性必须是字符串:

    LauncherComponent.LauncherComponent {
        id: launcherComponentId
        objectName: "launcherComponent"
        height: parent.height
        width: parent.width
        anchors.centerIn: parent
    }
    
    • 另一个错误是,如果你打算使用ApplicationWindow,你不应该使用QQuickView,因为ApplicationWindow创建了一个顶层并且QQuickView,所以你将有2个顶层,你正在寻找的儿子QQuickView 但不在 ApplicationWindow 孩子中,所以我建议您将 .py 修改为:

    import sys
    
    from PyQt5.QtCore import *
    from PyQt5.QtGui import *
    from PyQt5.QtQml import *
    
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.load(QUrl("module/Layout.qml"))
    if len(engine.rootObjects()) == 0:
        sys.exit(-1)
    print(engine.rootObjects()[0].findChild(QObject, 'launcherComponent'))
    sys.exit(app.exec_())
    

    也就是说,你必须使用QQmlApplicationEngine

    【讨论】:

    • 感谢您的回答,成功了!我正在阅读文档,但没有找到像您这样的解释。我将对这个引擎类进行一些研究。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多