Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I wish to access the GUI and close but I get X error:

Bad implementation(...).

How can I resolve this problem?

like image 607
Alin Avatar asked Mar 23 '23 17:03

Alin


1 Answers

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_()
like image 186
abhishekgarg Avatar answered Apr 25 '23 04:04

abhishekgarg