Home >Backend Development >Python Tutorial >How Can I Prevent Losing Custom Code When Redesigning Qt Designer UIs?
When utilizing Qt Designer to design graphical user interfaces (GUIs) for Python, it's possible to encounter a frustrating issue: modifications made to the generated Python code are lost when the UI is redesigned. This can be a significant inconvenience, especially when you've invested considerable effort in customizing the code for specific functionalities.
The key to solving this problem lies in separating the UI design from the code that handles the UI's functionality. Instead of directly modifying the generated Python code, create a new class that uses the design but handles the logic separately.
Consider the following example using the MainWindow template from Qt Designer:
Ui_MainWindow.py
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): [...] def retranslateUi(self, MainWindow): [...]
logic.py
from Ui_MainWindow import Ui_MainWindow class Logic(QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self)
By employing this approach, you can make changes to the design in Qt Designer without affecting the code in logic.py.
The choice of the PyQtClass depends on the design template chosen:
Template | PyQtClass |
---|---|
Main Window | QMainWindow |
Widget | QWidget |
Dialog with Buttons Bottom | QDialog |
Dialog with Buttons Right | QDialog |
Dialog with Without Buttons | QDialog |
This implementation allows for advanced logic implementation within the logic class, such as handling window close events. Here's an example:
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()
The above is the detailed content of How Can I Prevent Losing Custom Code When Redesigning Qt Designer UIs?. For more information, please follow other related articles on the PHP Chinese website!