Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python findChild返回None_Python_Pyqt_Qml_Pyqt5 - Fatal编程技术网

Python findChild返回None

Python findChild返回None,python,pyqt,qml,pyqt5,Python,Pyqt,Qml,Pyqt5,我看到其他人问这个问题,但我试过的都不管用。 我正在使用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_trac

我看到其他人问这个问题,但我试过的都不管用。 我正在使用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属性放在一个矩形对象中,我想也许一个更通用的会起作用。所有这些都不起作用。

您的代码有几个错误:

  • objectName
    属性必须是字符串:

  • 另一个错误是,如果要使用
    ApplicationWindow
    ,则不应使用
    QQuickView
    ,因为
    ApplicationWindow
    会创建顶级和
    QQuickView
    ,因此您将有两个顶级,并且您正在寻找
    QQuickView
    的儿子,但不在
    ApplicationWindow
    儿童,因此我建议您将.py修改为:

也就是说,您必须使用
QQmlApplicationEngine

谢谢您的回答,它成功了!我正在阅读文档,但没有找到像你这样的解释。我会做一些关于这类引擎的研究。
LauncherComponent.LauncherComponent {
    id: launcherComponentId
    objectName: "launcherComponent"
    height: parent.height
    width: parent.width
    anchors.centerIn: parent
}
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_())