目前我正在使用pycharm来开发python web应用程序.我想用QT框架开发桌面应用程序.我已经安装了pyqt.我在pyqt中搜索了hello world并找到了这个:
from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.button = QtGui.QPushButton('Test', self) self.button.clicked.connect(self.handleButton) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.button) def handleButton(self): print ('Hello World') if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())
但是我不知道在哪里放这个代码?这是我的pyqt设计师看起来像:
是否可以告诉我在哪里编写代码以及如何处理按钮单击?
看起来您发布的代码是从我的这个答案中复制的.该代码是一个简单的手写示例,完全不涉及使用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中打开.
首先要了解的是Qt Designer,它不是IDE - 它只用于设计GUI,而不是主程序逻辑.程序逻辑单独编写,然后连接到GUI.
有两种方法可以做到这一点.第一种是ui
使用uic模块直接加载文件:
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类相匹配(在本例中也称为"Window",但可以是你喜欢的任何东西).其他GUI小部件成为子类的属性 - 因此QPushButton可用作self.button
.
将GUI与程序逻辑连接起来的另一种方法是使用pyuic工具从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
.