Home >Backend Development >Python Tutorial >How to Preserve Custom Code When Redesigning Qt Designer UIs in Python?
When using Qt Designer to create GUIs for Python applications, it's frustrating to lose custom code changes upon subsequent UI redesigns. This article explores a solution to this problem and introduces the concept of splitting logic into separate Python files.
To avoid losing code changes when redesigning UI using Qt Designer, it's recommended to create a secondary file that implements the GUI logic, while keeping the generated code from Qt Designer separate.
For instance, if the MainWindow template is used in "design.ui," convert it to "Ui_Design.py" and create a new file "logic.py" for implementing logic.
# Ui_Design.py (Generated from Qt Designer) from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): [...] def retranslateUi(self, MainWindow): [...] # logic.py from PyQt5 import QtCore, QtGui, QtWidgets from Ui_Design import Ui_MainWindow class Logic(QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self)
Using this approach ensures that UI changes made in Qt Designer will not overwrite custom code in "logic.py."
To further organize and maintain code, you can split the logic class into multiple files, ensuring each file focuses on a specific aspect of the functionality.
To achieve this, the logic class must follow a specific structure:
class Logic(PyQtClass, DesignClass): def __init__(self, *args, **kwargs): PyQtClass.__init__(self, *args, **kwargs) self.setupUi(self)
Where:
As an example of implementing logic in separate files, consider creating a close event handler that displays a confirmation message box before closing the PyQt application.
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()
By splitting code into separate files and following the logic class structure, you can easily maintain and extend your Qt-based Python applications while preserving custom code changes amidst UI redesigns.
The above is the detailed content of How to Preserve Custom Code When Redesigning Qt Designer UIs in Python?. For more information, please follow other related articles on the PHP Chinese website!