将.ui文件转换为.py文件后,如何再次使用QtDesigner编辑应用?
Absolutely—this is totally supported and actually the intended workflow for QtDesigner! The whole point of separating the UI design (in .ui files) from your application logic is to let you iterate on the design easily without breaking your code.
Here's the step-by-step process to do this correctly:
Keep your original
.uifile safe: This is your single source of truth for the UI layout. If you somehow lost it, you can convert the generated.pyfile back to.uiusing the command:pyuic5 -x your_generated_file.py -o restored_ui_file.uiBut pro tip: always keep the original
.uifile stored somewhere you won't overwrite it.Make changes in QtDesigner: Open your
.uifile in QtDesigner, tweak the layout, add/remove widgets, adjust properties—whatever changes you need. Save the updated.uifile when you're done.Re-generate the
.pyfile: Use the samepyuic5command you used initially to convert the updated.uito.py. For example:pyuic5 your_updated_ui.ui -o your_generated_file.py
Critical Note: Don't edit the generated .py file directly!
If you've added custom code (like signal-slot connections, business logic, or custom widget behavior) to the auto-generated .py file, those changes will get overwritten every time you re-convert from .ui to .py. Instead, follow the recommended best practice:
- Treat the auto-generated
.pyfile (let's call itui_main.py) as read-only. - Create a separate file (e.g.,
app.py) where you import the UI class fromui_main.py, subclass it, and add all your custom code there.
Here's a quick example of this structure:
app.py:
from PyQt5.QtWidgets import QMainWindow, QApplication from ui_main import Ui_MainWindow # Import the auto-generated UI class class MyApp(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) # Initialize the UI from the generated file # Add your custom logic here—this won't be overwritten! self.my_button.clicked.connect(self.handle_button_click) def handle_button_click(self): self.statusBar().showMessage("Button clicked!") if __name__ == "__main__": import sys app = QApplication(sys.argv) window = MyApp() window.show() sys.exit(app.exec_())
This way, you can modify the UI in QtDesigner as much as you want, re-generate the .py file, and your custom application logic stays completely intact.
内容的提问来源于stack exchange,提问作者Animesh Singh

