Qt GUI inside loop?

1915 views python
0

What I want to achieve is a Qt Widget loop.

Simple example:

UI_dialog is a QDialog and after accepted it will open UI_mainwindow which is a QMainWindow.

There is a button in UI_mainwindow and if clicked, it will close UI_mainwindow and go back to UI_dialog.

What I've done so far:

I've tried:

create while loop in a Qthread which contains the two UI objects call UI_dialog inside UI_mainwindow (kind of succeed but may crash sometimes for my poor design)

answered question

1 Answer

9

In a GUI you must avoid the while True, the GUI already has an internal while True that allows you to listen to the events and according to it do the internal tasks. On the other hand the threads should be your last option since the GUI should not update from another thread directly, it should only be used if there is a blocking task.

In the case of Qt there are signals that allow notification of changes, this will be connected to functions so that the latter is invoked when the signal is emited.

from PyQt5 import QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.button = QtWidgets.QPushButton("Press me")
        self.setCentralWidget(self.button)
        self.button.clicked.connect(self.close)

class Dialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        buttonBox = QtWidgets.QDialogButtonBox()
        buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(buttonBox)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w1 = MainWindow()
    w2 = Dialog()
    w1.button.clicked.connect(w2.show)
    w2.accepted.connect(w1.show)
    w2.show()
    sys.exit(app.exec_())

posted this

Have an answer?

JD

Please login first before posting an answer.