PyQt5 中的前后端分离与 QML
Posted
技术标签:
【中文标题】PyQt5 中的前后端分离与 QML【英文标题】:Front-end and Back-end Separation in PyQt5 with QML 【发布时间】:2019-03-22 09:12:54 【问题描述】:我想将 QML UI 添加到现有的 Python 线程任务中,但我不知道该怎么做才能不过多更改任务以保持前端和后端分离。
让我用一个最小化的例子来解释这个问题。我想用 QML 添加 GUI 来控制进程(或线程)的启动和停止,以及从进程中获取和显示信息。例如,以下是一些繁重的工作流程。
class Task(threading.Thread):
def __init__(self):
super().__init__()
self.num = 0
def run(self):
for i in range(35):
self.num = fib(i)
def fib(N):
if N <= 1:
return 1
return fib(N - 1) + fib(N - 2)
现在,我尝试创建一个 QML 文件,以在 Task
之后的 Task().start()
中获取 self.num
而不会阻塞。
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?根据this question,我尝试创建一个Backend
类来处理前端和后端之间的任何通信,并将上下文属性设置为QML (engine.rootContext().setContextProperty("backend", Backend())
)。例如,
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()
不过,我不知道如何双向绑定backend
中的self.num
和t.num
。因此,在 QML UI 中的按钮调用 start_process()
后,我无法实时更新 t.num
。
我想尽量减少对Task
的修改,因为它是旧程序的核心功能。因此,Simple Example in PyQt5 website 无法满足我的要求。
此外,如果我想将 Python threading.Thread
更改为 multiprocessing.Process
,我应该怎么做才能在每次更新过程中获取变量以便在 QML UI 上显示?
【问题讨论】:
【参考方案1】:首先,您不需要像 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_())
【讨论】:
那么,这是否意味着我仍然需要修改Task
以添加一些功能才能发送信号?不修改其中的任何代码就无法扩展旧类并连接到QML UI吗?
@SeanWu 我已经给了你至少 3 种侵入性最小的方法,所以答案是:你必须修改 Task 类。以上是关于PyQt5 中的前后端分离与 QML的主要内容,如果未能解决你的问题,请参考以下文章