Прежде всего, вам не нужен такой установщик, как qproperty, так как в соответствии с вашей логикой вы не должны изменять qproperty из QML.С другой стороны, вы должны передать бэкэнд своему потоку через 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_())
Другое решение состоит в том, что он больше не наследует от многопоточности. Но от 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_())