1

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

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

错误:列表索引超出范围

奇怪的是,当我在 MouseArea 单击后尝试调用 foo.init_window() 时,它会起作用。

这是我的python代码:

主文件

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....")
            }
        }
    }
}
4

1 回答 1

1

问题是Component.onCompleted窗口中(rootObject)已完成构建但引擎列表尚未更新。解决方案是稍后使用以下命令调用 init_window Qt.callLater()

Component.onCompleted: Qt.callLater(foo.init_window)
于 2020-11-19T16:43:13.330 回答