0

I have a python script that does its job fairly well. It's been built around a socket and various string processes, and works fine. But now I am slapping a GUI onto the thing, and I am running into issues where the GUI blocks the remainder of the script until it has exited, so the question then is, how do I keep the Qt5 GUI while still allowing a mainloop to run in the background?

class Gui(Thread):
    def __init__(self):
        Thread.__init__(self)

        app = QApplication(sys.argv)
        mainWin = QWidget()
        mainWin.resize(640, 480)

        winArea = QMdiArea(mainWin)
        mainLayout = QVBoxLayout()
        mainLayout.setStretch(1, 1)
        mainLayout.addWidget(winArea)
        mainWin.setLayout(mainLayout)

        consoleWindow = ConsoleWindow()
        winArea.addSubWindow(consoleWindow)

        mainWin.show()
        app.exec()


class ConsoleWindow(QMdiSubWindow):
    def __init__(self):
        super(ConsoleWindow, self).__init__()
        self.consoleContents = QWidget()
        self.buffer = QTextEdit()
        self.buffer.setReadOnly(True)
        self.input = QLineEdit()

        self.consoleLayout = QVBoxLayout(self.consoleContents)
        self.consoleLayout.addWidget(self.buffer)
        self.consoleLayout.addWidget(self.input)

        self.consoleContents.setLayout(self.consoleLayout)
        self.setWidget(self.consoleContents)
        self.setWindowTitle('Console')


gui = Gui()

# SNIP: Setting up a socket and some file handles goes here

while True:
    # SNIP: Do some mainloop stuff with sockets and files. With tkinter I had this loop also update the GUI.

As you can see from the Gui class, I tried to implement threading, and launch the GUI in a separate thread, but I am probably not going about it the right way, as it's based on an example I came across that used multithreading to deal with several clients connecting to a socket.

Jarmund
  • 3,003
  • 4
  • 22
  • 45
  • 1
    Well you have to do the opposite: move the other part of your application (sockets, etc) to the other thread and keep the GUI in the main thread. – eyllanesc May 10 '20 at 17:45
  • Alright, I'll try that, then. Any particular reason why? – Jarmund May 10 '20 at 18:24
  • In general the GUI should be executed in the main thread and that is mandatory in Qt. But the underlying reason is that a GUI is complex software where thousands of objects interact, and between QObjects, which for efficiency reasons are not thread-safe, so if a QObject (such as widgets) are modified, it is another thread. then a lot of things can go wrong (bad timing etc). Read https://doc.qt.io/qt-5/thread-basics.html#gui-thread-and-worker-thread – eyllanesc May 10 '20 at 18:46

0 Answers0