看起来您发布的代码是从我的this answer 复制的。该代码是一个简单的手写示例,根本不涉及使用 Qt Designer。
使用 Qt Designer 的“Hello World”示例将从 ui 文件开始,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Window</class>
<widget class="QWidget" name="Window">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>171</width>
<height>61</height>
</rect>
</property>
<property name="windowTitle">
<string>Hello World</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QPushButton" name="button">
<property name="text">
<string>Test</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
这个文件可以保存为helloworld.ui并在Qt Designer中打开。
首先要了解Qt Designer,它不是一个IDE——它只用于设计GUI,而不是主要的程序逻辑。程序逻辑单独编写,之后连接到GUI。
有两种方法可以做到这一点。第一种是直接加载ui文件,使用uic module:
import sys, os
from PyQt4 import QtGui, QtCore, uic
DIRPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)))
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
uic.loadUi(os.path.join(DIRPATH, 'helloworld.ui'), self)
self.button.clicked.connect(self.handleButton)
def handleButton(self):
print('Hello World')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
这会将 GUI 注入到本地 Window 类中,该类是与 Qt Designer 中的顶级 GUI 类匹配的子类(在这种情况下也称为“窗口”,但可以是任何你喜欢的东西)。其他 GUI 小部件成为子类的属性 - 因此 QPushButton 可用作 self.button。
将 GUI 与程序逻辑连接的另一种方法是使用 pyuic tool 从 ui 文件生成 python 模块:
pyuic4 --output=helloworld.py helloworld.ui
然后可以导入到主应用程序中:
import sys
from PyQt4 import QtGui, QtCore
from helloworld import Ui_Window
class Window(QtGui.QWidget, Ui_Window):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
self.button.clicked.connect(self.handleButton)
def handleButton(self):
print('Hello World')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
setupUi 方法继承自生成的Ui_Window 类,与uic.loadUi 做的事情完全相同。