如何从PyQt中的另一个线程访问GUI元素 [英] How to access GUI elements from another thread in PyQt
本文介绍了如何从PyQt中的另一个线程访问GUI元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个客户端-服务器应用程序,并且当服务器关闭时,我希望关闭客户端GUI,而该线程正在另一个线程上运行.我希望访问GUI并关闭,但出现X错误:错误的实现(...).我如何解决这个问题?
I'm trying to create a client-server application, and when the server closes I wish that client GUI to close, wich is running on another thread. I wish to access the GUI and close but I get X error : Bad implementation(...). How cand I resolve this problem?
推荐答案
您所能做的就是在第一个线程关闭时发出自定义信号.
what you can do is emit a custom signal when the first thread goes down..
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_()
这篇关于如何从PyQt中的另一个线程访问GUI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文