如何从pyuic5生成的.py文件恢复QT5 .ui文件?误删分支致文件丢失
Great question—this is a super common headache when you accidentally lose source UI files, so let’s break down what’s possible and what isn’t.
The Short Answer
You cannot fully restore the exact original .ui file from the pyuic5-generated .py file. The conversion from .ui (XML-based) to .py is effectively one-way in terms of preserving all metadata: pyuic5 discards non-functional details like Qt Designer's visual editing hints, XML comments, and some hidden layout attributes that aren't needed for runtime execution.
What You Can Do
You can create a functional equivalent .ui file that replicates the behavior of the original, using the .py file as a detailed blueprint. Here are your best options:
1. Manual Reconstruction in Qt Designer (Most Reliable)
This is the go-to method for complex interfaces:
- Open Qt Designer and start with a new form matching the base widget type from your .py file (e.g.,
QMainWindow,QWidget). - Walk through the .py code line by line:
- For every widget initialization (like
self.pushButton = QPushButton(self)), add the same widget type to your Designer form. - Copy over properties like text, tooltips, or stylesheets from lines such as
self.pushButton.setText("Submit")orself.pushButton.setStyleSheet("background-color: #4CAF50;"). - Recreate layouts by matching the layout setup code (e.g.,
self.horizontalLayout = QHBoxLayout(self.centralwidget)translates to adding a horizontal layout in Designer). - Reconnect signal-slot connections using Designer’s signal/slot editor, referencing lines like
self.pushButton.clicked.connect(self.on_pushButton_clicked).
- For every widget initialization (like
2. Third-Party Scripts for Basic Conversion (For Simple Interfaces)
For straightforward UIs, some community-developed scripts can parse pyuic5 output and generate a rough .ui XML file. These tools scan the .py code for widget creation and layout logic, then map that to the corresponding .ui XML structure.
Keep in mind their limitations:
- They often struggle with custom widgets, dynamic layout adjustments, or complex signal-slot logic.
- They won’t restore visual editor-specific details (like guide lines or groupings you used in Designer).
If you want to try this, you can write a basic Python script yourself to parse key elements, or look for existing open-source scripts tailored to this task.
Key Limitations to Expect
Even with the best approach, you won’t get back:
- Original comments from the .ui XML file
- Qt Designer-specific metadata (like layout anchors or editing history)
- Exact pixel-perfect positioning if the original used absolute layouts (though you can approximate this)
- Hidden or deprecated properties that pyuic5 didn’t include in the .py output
内容的提问来源于stack exchange,提问作者uMinded

