gpt4 book ai didi

python - findChild 返回 None

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:58 24 4
gpt4 key购买 nike

我看到其他人问过这个问题,但我尝试过的都没有用。我正在使用 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 对象中,我认为可能更通用的一个会起作用。这些都不起作用。

最佳答案

您的代码有几个错误:

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

LauncherComponent.LauncherComponent {
id: launcherComponentId
objectName: "launcherComponent"
height: parent.height
width: parent.width
anchors.centerIn: parent
}
  • 另一个错误是,如果您要使用 ApplicationWindow,则不应使用 QQuickView,因为 ApplicationWindow 创建顶层,而 QQuickView 所以你将有 2 个顶层,你正在寻找 QQuickView 的儿子,但不在 ApplicationWindow child 中,所以我建议你修改你的 .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

关于python - findChild 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49078973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com