如何从PyQt中的另一个线程访问GUI元素

时间:2013-06-04 13:41:19

标签: python multithreading pyqt

我正在尝试创建一个客户端 - 服务器应用程序,当服务器关闭时,我希望关闭客户端GUI,这是在另一个线程上运行。我希望访问GUI并关闭,但我得到X错误:错误的实现(...)。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:7)

当第一个线程关闭时,您可以做的是发出自定义信号..

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_()