PyQt5 findChild返回None

问题描述 投票:1回答:1

我看到其他人问这个问题,但没有我尝试过的工作。我正在使用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
1个回答
1
投票

您的代码有几个错误:

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

LauncherComponent.LauncherComponent {
    id: launcherComponentId
    objectName: "launcherComponent"
    height: parent.height
    width: parent.width
    anchors.centerIn: parent
}
  • 另一个错误是,如果你打算使用ApplicationWindow你不应该使用QQuickView,因为ApplicationWindow创建了一个顶层和QQuickView所以你将有2个toplevels你正在寻找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

© www.soinside.com 2019 - 2024. All rights reserved.