Skip to content Skip to sidebar Skip to footer

Msgbox Error While Threading , GUI Blocks

I have a problem while executing the following gui. it works normally if there's no msgbox, but when there is a mesbox it blocks. any idea why the gui blocks when there is message.

Solution 1:

Any access to UI elements is only allowed from within the main Qt thread. Note that access means not only reading/writing widget properties, but also creation; any attempt to do so from other threads results in graphical issues or incosistent behavior in the best case, and a crash in the worst (and more common) case.

The only correct way to do so is to use a QThread with (possibly) custom signals: this allows Qt to correctly queue signals and react to them when it can actually process them.

The following is a very simple situation that doesn't require creating a QThread subclass, but consider that this is just for educational purposes.

class Ui_MainWindow(object):
    # ...

    def calculation(self):
        for i in range(10):
            time.sleep(1)
            print(i)

    def showMessage(self):
        msg = QtWidgets.QMessageBox()
        msg.setInformativeText('Finish')
        msg.exec_()   
        self.pushButton.setEnabled(True)

    def threadingc(self):
        self.pushButton.setEnabled(False)
        self.thread = QtCore.QThread()
        # override the `run` function with ours; this ensures that the function
        # will be executed in the new thread
        self.thread.run = self.calculation
        self.thread.finished.connect(self.showMessage)
        self.thread.start()

Please consider the following important aspects:

  • I had to disable the pushbutton, otherwise it would be possible to create a new thread while the previous one still executing; this will create a problem, since overwriting self.thread will cause python to try to garbage collect (delete) the previous thread while running, which is a very bad thing;
  • a possible solution to this is to create the thread with a parent, which is usually done with a simple QThread(self), but that's not possible in your case because Qt objects can accept only other Qt objects as their parent, while in your case self would be a Ui_MainWindow instance (which is a basic python object);
  • the above point is an important issue, because you're trying to implement your program starting from a pyuic generated file, which should never be done: those files are intended to be left as they are without any manual modification, and used only as imported modules; read more about this topic on the official guidelines about using Designer; also note that trying to mimic the behavior of those files is useless, as normally leads to great confusion about object structure;
  • you could theoretically add a reference to a qt object (for example, by adding self.mainWindow = MainWindow in the setupUi() function) and create the thread with that reference (thread = QThread(self.mainWindow)), or add the thread to a persistent list (self.threads = [], again in the setupUi()), but due to the above point I strongly discourage you to do so;

Finally, a more correct implementation of your code would require you to generate again the ui file, leave it as it is and do something like the following example; note that I added a very basic exception implementation that also shows how to correctly interact with custom signals.

from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow
import time

class Calculation(QtCore.QThread):
    error = QtCore.pyqtSignal(object)
    def run(self):
        for i in range(10):
            time.sleep(1)
            print(i)
            try:
                10 / 0
            except Exception as e:
                self.error.emit(e)
                break


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.pressed.connect(self.threadingc)

    def showMessage(self):
        msg = QtWidgets.QMessageBox()
        msg.setInformativeText('Finish')
        msg.exec_()   

    def threadingc(self):
        # create the thread with the main window as a parent, this is possible 
        # since QMainWindow also inherits from QObject, and this also ensures
        # that python will not delete it if you want to start another thread
        thread = Calculation(self)
        thread.finished.connect(self.showMessage)
        thread.error.connect(self.showError)
        thread.start()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

In the above case, the ui file was processed using the following command (assuming that the ui is named "mainwindow.ui", obviously):

pyuic mainwindow.ui -o mainwindow.py

Post a Comment for "Msgbox Error While Threading , GUI Blocks"