QtDesigner changes will be lost after redesign User Interface

To avoid having these problems it is advisable not to modify this file but to create a new file where we implement a class that uses that design.

For example, suppose you have used the MainWindow template in the design.ui file, then convert it to Ui_Design.py like to the following structure:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        [...]

    def retranslateUi(self, MainWindow):
        [...]

Then we will create a new file that we will call logic.py where we will create the file that handles the logic and that uses the previous design:

class Logic(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)

So even if you modify the design and generate the file again .py you will not have to modify the file of the logic.

To generalize the idea we must have the following rules but for this the logic class must have the following structure:

class Logic(PyQtClass, DesignClass):
    def __init__(self, *args, **kwargs):
        PyQtClass.__init__(self, *args, **kwargs)
        self.setupUi(self)
  • PyQtClass: This class depends on the design chosen.

   Template                      PyQtClass
 ─────────────────────────────────────────────
   Main Window                   QMainWindow
   Widget                        QWidget 
   Dialog with Buttons Bottom    QDialog
   Dialog with Buttons Right     QDialog
   Dialog with Without Buttons   QDialog

  • DesignClass: The name of the class that appears in your design.

The advantage of this implementation is that you can implement all the logic since it is a widget, for example we will implement the solution closing pyqt messageBox with closeevent of the parent window :

class Logic(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
    def closeEvent(self, event):
        answer = QtWidgets.QMessageBox.question(
            self,
            'Are you sure you want to quit ?',
            'Task is in progress !',
            QtWidgets.QMessageBox.Yes,
            QtWidgets.QMessageBox.No)
        if answer == QtWidgets.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

Leave a Comment