从Component.onCompleted中的QQmlApplicationEngine获取根对象时出错

2024-10-02 06:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在窗口完成后获取根对象,但出现错误:

QmlObj = self.engine.rootObjects()[0]

Error: list index out of range

奇怪的是,当我尝试在鼠标earea点击后调用foo.init_window()时,它就起作用了

以下是我的python代码:

main.py

from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QObject, QUrl, Slot

import sys
import win32gui

flag = False


class Foo(QObject):
    def __init__(self):
        super().__init__()
        self.engine = QQmlApplicationEngine()

    @Slot()
    def init_window(self):
        global flag
        if not flag:
            QmlObj = self.engine.rootObjects()[0]
            desk = win32gui.FindWindow("Progman", "Program Manager")
            print(desk)
            sndWnd = win32gui.FindWindowEx(desk, 0, "SHELLDLL_DefView", None)
            print(sndWnd)
            targetWnd = win32gui.FindWindowEx(sndWnd,
                                              0, "SysListView32", "FolderView")
            print(targetWnd)
            win32gui.SetParent((int)(QmlObj.winId()), targetWnd)
            flag = True


if __name__ == "__main__":
    app = QApplication(sys.argv)
    foo = Foo()

    foo.engine.rootContext().setContextProperty("foo", foo)
    foo.engine.load(QUrl("main.qml"))
    # win = foo.engine.rootObjects()[0]
    # win.show()

    if not foo.engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

以下是.qml文件:

main.qml

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.0

Window {
    width: 200
    height: 100
    visible: true
    //flags: Qt.FramelessWindowHint
    //flags: Qt.WindowStaysOnBottomHint
    //flags: Qt.WindowMinMaxButtonsHint

    Rectangle {
        anchors.fill: parent
        color: "red"

        Component.onCompleted: foo.init_window()

        MouseArea {
            anchors.fill: parent
            onClicked: foo.init_window()
        }

        Text {
            anchors.centerIn: parent
            text: "Hello, World!"
        }

        Button {
            text: "Ok"
            onClicked: {
                console.log("OK Button clicked....")
            }
        }
    }
}

Tags: fromimportselfiffooinitmainsys
1条回答
网友
1楼 · 发布于 2024-10-02 06:28:24

问题在于Component.onCompleted中的窗口(rootObject)已完成构建,但引擎列表尚未更新。解决方案是稍后使用Qt.callLater()调用init_窗口:

Component.onCompleted: Qt.callLater(foo.init_window)

相关问题 更多 >

    热门问题