Python findChild返回None
我看到其他人问这个问题,但我试过的都不管用。 我正在使用PyQt 5.10.1。 下面是python代码: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
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
儿童,因此我建议您将.py修改为:ApplicationWindow
也就是说,您必须使用
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_())