【发布时间】:2020-01-31 14:32:09
【问题描述】:
我有一个 python 定义的工作人员 QObject,它有一个慢速 work() 插槽,由 QML UI 调用(在我的实际 UI 中,该方法在 FolderListModel 中的每个项目上作为用户动态调用遍历列表,但对于他的示例代码,我只是在窗口完成时调用它作为示例)。
我想异步运行慢速 work 以防止 UI 阻塞。我想通过在 QThread 上移动 Worker 实例并在那里调用插槽来做到这一点,但这不起作用,因为 UI 仍然被阻止等待 work() 的结果。
这是我目前尝试的代码:
mcve.qml:
import QtQuick 2.13
import QtQuick.Window 2.13
Window {
id: window
visible: true
width: 800
height: 600
title: qsTr("Main Window")
Component.onCompleted: console.log(worker.work("I'm done!")) // not the actual usage, see note in the question
}
mcve.py:
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QUrl, QThread, QObject, Slot
from time import sleep
class Worker(QObject):
def __init__(self, parent=None):
super().__init__(parent)
@Slot(str, result=str)
def work(self, path):
sleep(5) # do something lengthy
return path
if __name__ == '__main__':
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
workerThread = QThread()
worker = Worker()
worker.moveToThread(workerThread)
engine.rootContext().setContextProperty("worker", worker)
engine.load(QUrl.fromLocalFile('mcve.qml'))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
如何异步调用work(),以便只有在它完成后才会应用其效果?而且,作为奖励,我在使用 QThreads 时做错了什么/理解错误?
【问题讨论】:
标签: python qt qml qthread pyside2