I am a PyQt 5.4.1-1
初学者,我的Python是3.4.3
。这是我尝试遵循的many https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ 博文 http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/ and SO https://stackoverflow.com/questions/16241297/how-to-signal-from-a-running-qthread-back-to-the-pyqt-gui-that-started-it的问题proper™ 创建线程的方法(即没有 QThread 子类化):
#!/usr/bin/env python3
from PyQt5.QtCore import QObject, QThread
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
print("Base init")
self.thread = QThread()
w = Worker()
w.finished[int].connect(self.onFinished)
w.moveToThread(self.thread)
self.thread.started.connect(w.work)
self.thread.start()
@pyqtSlot(int)
def onFinished(self, i):
print("Base caught finished, {}".format(i))
class Worker(QObject):
finished = pyqtSignal(int)
def __init__(self):
print("Worker init")
super().__init__()
def work(self):
print("Worker work")
Worker.finished.emit(42)
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
在写这个问题时,我意识到如果进行以下更改,那么一切似乎都有效:
...
self.w = Worker()
self.w.finished[int].connect(self.onFinished)
self.w.moveToThread(self.thread)
self.thread.started.connect(self.w.work)
...
...
self.finished.emit(42)
...
但我不明白为什么这有帮助。为什么我必须制作一个非 Gui 相关的Worker
Gui 类的实例成员?坦白说,感觉不对。现在关于信号:这是一个类属性 https://docs.python.org/3.4/tutorial/classes.html#class-and-instance-variables那么为什么调用之间存在差异Worker.finished.emit(42)
它在运行时失败并且self.finisehd.emit(42)
当我期望没有差异时它会成功(这是一个类属性!)
首先,Python 是一种自动垃圾收集的语言。你的变量w
超出范围__init__
方法,并在该方法返回后立即被垃圾收集。这就是为什么事情第一次没有按照你预期的方式进行。使变量成为类的成员可确保它不会超出范围,而MainWindow
实例存在。
你的第二个问题有点难以回答,但我敢打赌,通过查看信号在 PySide/PyQt 中的工作原理,你将获得宝贵的见解Q元对象 http://srinikom.github.io/pyside-docs/PySide/QtCore/QMetaObject.html文档。
--EDIT--
为你的第二个问题找到了更好的答案here https://stackoverflow.com/questions/15025686/why-does-pyside-implicitely-create-object-members-from-class-members-for-signals.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)