我想将QML UI添加到一个现有的Python线程任务中,但是我不知道如何做得太多而又不改变任务以保持前端和后端分离。
让我用一个最小化的例子来解释这个问题。我想添加带有QML的GUI来控制进程(或线程)的启动和停止以及获取和显示进程信息。例如,以下是一些繁重的工作。
self.num
现在,我尝试创建一个QML文件,以在Task
之后获得Task().start()
中的import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow {
visible: true
Column {
Button {
text: 'hello'
onClicked: {
backend.start_process()
}
}
Text {
text: backend.num
}
}
}
,而不会阻塞。
Task
为了保持前端和后端分离,是否有任何方法可以将Task
连接到QML UI,而无需更改Backend
中的任何脚本内容?根据{{3}},我尝试创建一个engine.rootContext().setContextProperty("backend", Backend())
类来处理前端和后端之间的任何通信,并将context属性设置为QML(class Backend(PyQt5.QtCore.QObject):
changed = PyQt5.QtCore.pyqtSignal(int)
def __init__(self):
super().__init__()
self._num = 0
@PyQt5.QtCore.pyqtProperty(int, notify=changed)
def num(self):
return self._num
@num.setter
def num(self, val):
if self._num == val:
return
self._num = val
self.changed.emit(self._num)
@PyQt5.QtCore.pyqtSlot()
def start_process(self):
t = Task()
t.start()
)。例如,
self.num
但是,我不知道如何双向绑定 t.num
中的backend
和t.num
。因此,在QML UI中的按钮调用start_process()
之后,我无法实时更新Task
。
我想最小化threading.Thread
的修改,因为它是旧程序的核心功能。因此,this question无法满足我的要求。
此外,如果我想将Python multiprocessing.Process
更改为{{1}},我应该怎么做才能在每次更新过程中获取变量以便在QML UI上显示?
答案 0 :(得分:0)
首先,您不需要像qproperty这样的设置器,因为根据您的逻辑,您不应从QML修改qproperty。另一方面,您必须通过args或kwargs将后端传递给线程,并发送调用插槽的信息:
import threading
import time
from PyQt5 import QtCore, QtGui, QtQml
class Task(threading.Thread):
def run(self):
self.backend = self._kwargs.get('backend')
for i in range(35):
num = fib(i)
if self.backend is not None:
QtCore.QMetaObject.invokeMethod(
self.backend,
"set_num",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(int, num)
)
time.sleep(0.01)
def fib(N):
if N <= 1:
return 1
return fib(N - 1) + fib(N - 2)
class Backend(QtCore.QObject):
changed = QtCore.pyqtSignal(int)
def __init__(self):
super().__init__()
self._num = 0
@QtCore.pyqtProperty(int, notify=changed)
def num(self):
return self._num
@QtCore.pyqtSlot(int)
def set_num(self, val):
if self._num == val:
return
self._num = val
self.changed.emit(self._num)
@QtCore.pyqtSlot()
def start_process(self):
Task(kwargs=dict(backend=self), daemon=True).start()
if __name__ == "__main__":
import os
import sys
app = QtGui.QGuiApplication(sys.argv)
backend = Backend()
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("backend", backend)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())
另一种方法是创建具有以下信息的QEvent:
import threading
import time
from PyQt5 import QtCore, QtGui, QtQml
class InfoEvent(QtCore.QEvent):
EventType = QtCore.QEvent.User
def __init__(self, info):
super(InfoEvent, self).__init__(InfoEvent.EventType)
self._info = info
@property
def info(self):
return self._info
class Task(threading.Thread):
def run(self):
self.backend = self._kwargs.get('backend')
for i in range(35):
num = fib(i)
if self.backend is not None:
event = InfoEvent(num)
QtCore.QCoreApplication.sendEvent(self.backend, event)
time.sleep(0.01)
def fib(N):
if N <= 1:
return 1
return fib(N - 1) + fib(N - 2)
class Backend(QtCore.QObject):
changed = QtCore.pyqtSignal(int)
def __init__(self):
super().__init__()
self._num = 0
def event(self, e):
if e.type() == InfoEvent.EventType:
self.set_num(e.info)
return True
return super(Backend, self).event(e)
@QtCore.pyqtProperty(int, notify=changed)
def num(self):
return self._num
@QtCore.pyqtSlot(int)
def set_num(self, val):
if self._num == val:
return
self._num = val
self.changed.emit(self._num)
@QtCore.pyqtSlot()
def start_process(self):
Task(kwargs=dict(backend=self), daemon=True).start()
if __name__ == "__main__":
import os
import sys
app = QtGui.QGuiApplication(sys.argv)
backend = Backend()
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("backend", backend)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())
另一种解决方案是它不再继承自threading.Thread,而是继承自QThread,后者实现了一些将信息发送到主线程的信号。
from PyQt5 import QtCore, QtGui, QtQml
class Task(QtCore.QThread):
valueChanged = QtCore.pyqtSignal(int)
def run(self):
for i in range(35):
num = fib(i)
self.valueChanged.emit(num)
QtCore.QThread.msleep(1)
def fib(N):
if N <= 1:
return 1
return fib(N - 1) + fib(N - 2)
class Backend(QtCore.QObject):
changed = QtCore.pyqtSignal(int)
def __init__(self):
super().__init__()
self._num = 0
@QtCore.pyqtProperty(int, notify=changed)
def num(self):
return self._num
@QtCore.pyqtSlot(int)
def set_num(self, val):
if self._num == val:
return
self._num = val
self.changed.emit(self._num)
@QtCore.pyqtSlot()
def start_process(self):
thread = Task(self)
thread.valueChanged.connect(self.set_num)
thread.start()
if __name__ == "__main__":
import os
import sys
app = QtGui.QGuiApplication(sys.argv)
backend = Backend()
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("backend", backend)
qml_path = os.path.join(os.path.dirname(__file__), "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(qml_path))
if not engine.rootObjects():
sys.exit(-1)
engine.quit.connect(app.quit)
sys.exit(app.exec_())