所以我一直在寻找如何使用QThreads和Signals的答案,并且得到了答案:
How to access GUI elements from another thread in PyQt
想知道这对其他人不起作用吗?窗户冻结了。我的电脑有什么问题或是答案吗?
代码是:
from PyQt4 import QtGui as gui
from PyQt4 import QtCore as core
import sys
import time
class ServerThread(core.QThread):
def __init__(self, parent=None):
core.QThread.__init__(self)
def start_server(self):
for i in range(1,6):
time.sleep(1)
self.emit(core.SIGNAL("dosomething(QString)"), str(i))
def run(self):
self.start_server()
class MainApp(gui.QWidget):
def __init__(self, parent=None):
super(MainApp,self).__init__(parent)
self.label = gui.QLabel("hello world!!")
layout = gui.QHBoxLayout(self)
layout.addWidget(self.label)
self.thread = ServerThread()
self.thread.start()
self.connect(self.thread, core.SIGNAL("dosomething(QString)"), self.doing)
def doing(self, i):
self.label.setText(i)
if i == "5":
self.destroy(self, destroyWindow =True, destroySubWindows = True)
sys.exit()
app = gui.QApplication(sys.argv)
form = MainApp()
form.show()
app.exec_()
答案 0 :(得分:0)
该代码适用于我Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32
。但是,该片段中有一个小错误:
您应该按此self.destroy(self, destroyWindow =True, destroySubWindows = True)
更改此行self.destroy(destroyWindow =True, destroySubWindows = True)
,否则您将收到此错误
TypeError:QWidget.destroy(bool destroyWindow = True,bool destroySubWindows = True):参数1具有意外类型' MainApp'