OpenSUSE下PyQt4生成代码运行无反应的问题求助
Hey there! I spot the issue immediately—your generated test_ui.py only defines the UI layout class, but it lacks the critical code to launch the Qt application and display the window. That’s why running it does nothing, even though basic Python scripts like your print test work perfectly.
Let’s walk through how to fix this:
Why this happens
The pyuic4 tool converts your .ui file into a Python class that describes your UI’s structure, but it doesn’t include the setup logic to actually run the app. Think of it as just the blueprint for your window, not the code to build and open it.
Solution 1: Add startup code to your generated UI file
Add this block to the very end of test_ui.py:
if __name__ == "__main__": app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_())
This code handles all the necessary steps to launch your UI:
- Creates a
QApplicationinstance (required for any Qt application to run) - Initializes the base widget window
- Attaches your UI layout to the window
- Makes the window visible
- Starts the Qt event loop to keep the app running until you close it
Now run python3 test_ui.py again, and your window should pop up!
Solution 2: Use a separate main script (recommended)
If you plan to regenerate the UI file later with pyuic4, any changes you make to test_ui.py will get overwritten. A better approach is to create a separate script (e.g., main.py) that imports and uses the UI class:
import sys from PyQt4 import QtGui from test_ui import Ui_Form if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = QtGui.QWidget() ui = Ui_Form() ui.setupUi(window) window.show() sys.exit(app.exec_())
Run this with python3 main.py—it works the same way, but you won’t lose your code when you update the UI later.
Quick check for PyQt4 installation
To rule out installation issues, run this command in your terminal:
python3 -c "from PyQt4 import QtGui; print('PyQt4 is installed correctly')"
If you don’t get an error, your PyQt4 setup is solid.
内容的提问来源于stack exchange,提问作者Ole A

