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

Error in getting the root object from QQmlApplicationEngine in Component.onCompleted

我尝试在 window 完成后获取根对象,但出现错误:

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

Error: list index out of range

奇怪的是,当我尝试在单击 MouseArea 后调用 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....")
            }
        }
    }
}

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

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