【问题标题】:Error in getting the root object from QQmlApplicationEngine in Component.onCompleted在 Component.onCompleted 中从 QQmlApplicationEngine 获取根对象时出错
【发布时间】:2021-03-03 00:38:22
【问题描述】:

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

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

错误:列表索引超出范围

奇怪的是,当我在 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....")
            }
        }
    }
}

【问题讨论】:

    标签: python qt qml pyside2 qqmlapplicationengine


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      相关资源
      最近更新 更多