简体   繁体   English

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

[英]How to access GUI elements from another thread in PyQt

I'm trying to create a client-server application, and when the server closes I wish that client GUI to close, which is running on another thread.我正在尝试创建一个客户端 - 服务器应用程序,当服务器关闭时,我希望关闭在另一个线程上运行的客户端 GUI。 I wish to access the GUI and close but I get X error:我希望访问 GUI 并关闭,但出现 X 错误:

Bad implementation(...).错误的实现(...)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM