PyQt GUI控制从另一个线程访问

时间:2013-06-05 15:55:59

标签: python multithreading user-interface

我正在尝试在python中创建一个客户端服务器应用程序。当服务器关闭时,我希望客户端的gui在一个单独的线程上关闭,但应用程序崩溃与Xlib错误:错误的实现...我已经搜索过,似乎是从其他线程访问GUI界面。我该怎么办?从其他线程访问python gui

1 个答案:

答案 0 :(得分:1)

这可能对你有帮助..

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