代码之家  ›  专栏  ›  技术社区  ›  Julien Séveno-Piltant

findChild返回None

  •  3
  • Julien Séveno-Piltant  · 技术社区  · 7 年前

    我看到其他人问这个问题,但我尝试的方法都没有奏效。 我正在使用 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属性放在一个矩形对象中,我想也许可以用一个更通用的方法。这一切都不起作用。

    1 回复  |  直到 6 年前
        1
  •  2
  •   eyllanesc Yonghwan Shin    7 年前

    您的代码有几个错误:

    • 这个 objectName 属性必须是字符串:

    LauncherComponent.LauncherComponent {
        id: launcherComponentId
        objectName: "launcherComponent"
        height: parent.height
        width: parent.width
        anchors.centerIn: parent
    }
    
    • 另一个错误是,如果要使用 ApplicationWindow 您不应该使用 QQuickView 自从 应用程序窗口 创建顶层,并 QQuickView 同样,你将有2个顶级水平,你正在寻找 QQuickView 但不是在 应用程序窗口 孩子们,所以我建议你修改你的。副本收件人:

    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 .