【发布时间】:2023-03-06 11:39:01
【问题描述】:
我有一个显示简单 UI 的 Python PyQt 应用程序。 当用户单击 UI 中的按钮时,它会触发 QThread。 线程的使用可以防止 UI 在线程运行时“冻结”。 我发出信号将信息从运行线程传递回 UI 以进行状态更新并指示完成。一切正常,如所述,我创建了一个简单的类供我的 UI 调用,它创建线程并运行我的通用处理。
但是,我还想为我的程序创建一个命令行版本(无 GUI)并使用相同的处理 QThread 类。但是,当我尝试连接信号时出现以下错误。 QThread 似乎只适用于 GUI 程序?
AttributeError: MyClass instance has no attribute 'connect'
是否可以将 QThread 与非 GUI 程序一起使用?
from PyQt4 import QtCore
from PyQt4.QtCore import *
#======================================
class MyProcess(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.quit()
self.wait()
def run(self):
print "do time intensive process here"
self.emit( SIGNAL('processdone'), "emitting signal processdone")
return
#======================================
class MyClass(QObject):
def __init__(self, parent=None): # All QObjects receive a parent argument (default to None)
super(MyClass, self).__init__(parent) # Call parent initializer.
thread1 = MyProcess() # uses QThread and emits signal 'processdone'
self.connect( thread1, SIGNAL("processdone"), self.thread1done)
thread1.start()
def thread1done(self):
print "done"
#======================================
if __name__ == "__main__":
MyClass()
【问题讨论】:
-
这听起来像是一种正确的方法是反应你的代码。而不是扩展 QThread(或 python 标准库中的 Thread)有一个可以完成工作的类,并且可以用两者来实例化
-
你能在你的代码中显示 gui 和 nongui 版本之间的区别吗?
标签: python multithreading pyqt pyqt4