1 创建窗口
首先创建一个QApplication对象,然后创建一个窗口并显示,最后当用户关闭窗口后,退出程序。
其中app.exec()使程序持续运行,直到用户关闭窗口后,返回数值0,随后sys.exit(0)退出程序。
import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == "__main__":
app = QApplication([]) # 创建一个QApplication对象
window = QWidget() # 创建一个窗口
window.setWindowTitle("PyQt窗口") # 设置窗口标题
window.show() # 显示窗口
sys.exit(app.exec()) # 使程序持续运行,直到用户关闭窗口
运行程序后,弹出窗口如下:
2 在窗口中添加控件
为了在同一个窗口中显示多个控件,同时便于代码管理,通常将同一个窗口的代码写入一个类中。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton
"""创建窗口类Window,继承于类QWidget"""
class Window(QWidget):
"""定义初始化方法"""
def __init__(self):
super(Window, self).__init__() # 执行父类的初始化方法
label = QLabel("This is a label.", self) # 添加QLabel控件
button = QPushButton("This is a button.", self) # 添加QPushButton控件
label.move(100, 0) # 设置label位置
button.move(100, 30) # 设置button位置
if __name__ == "__main__":
app = QApplication([])
window = Window() # 创建一个Window实例窗口
window.show()
sys.exit(app.exec())
上述代码中,为了创建窗口window,先定义一个类Window,然后在Window类中定义控件QLabel和QPushButton,并使用move方法设定其位置。最后在主程序中通过实例化Window方法以实现该窗口。
运行程序后,弹出窗口如下:
3 使用布局对控件进行排列
为了使多个控件在窗口中排列得更整齐,使用布局对控件进行排列。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout
"""创建窗口类Window,继承于类QWidget"""
class Window(QWidget):
"""定义初始化方法"""
def __init__(self):
super(Window, self).__init__() # 执行父类的初始化方法
"""新建垂直、水平布局"""
vbox = QVBoxLayout() # 垂直布局
hbox = QHBoxLayout() # 水平布局
"""定义控件label、button_Yes、button_No"""
label = QLabel("This is a label.")
button_Yes = QPushButton("同意")
button_No = QPushButton("拒绝")
"""在水平布局hbox上添加控件button_Yes、button_No"""
hbox.addWidget(button_Yes)
hbox.addWidget(button_No)
"""在垂直布局vbox上添加控件label、水平布局hbox"""
vbox.addWidget(label)
vbox.addLayout(hbox)
"""在窗口类Window上添加垂直布局hbox"""
self.setLayout(vbox)
if __name__ == "__main__":
app = QApplication([])
window = Window()
window.show()
sys.exit(app.exec())
上述代码中,对于一个Label和两个QPushButton,想要将Label置于第一行,将两个QPushButton水平并列置于第二行。所以先定义一个水平布局QHBoxLayout,用于水平并列放置两个QPushButton;然后定义一个垂直布局QVBoxLayout,用于垂直排列Label和上述水平布局;最后将该垂直布局添加至Window类中。
运行程序后,弹出窗口如下:
4 设置按下按键执行的函数
在窗口中添加QPushButton后,设置按下按钮后执行一段函数。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
"""创建窗口类Window,继承于类QWidget"""
class Window(QWidget):
"""定义初始化方法"""
def __init__(self):
super(Window, self).__init__()
"""定义控件button"""
button = QPushButton(self)
button.setText("确定")
button.clicked.connect(self.ClickButton) # 将clicked信号与ClickButton槽函数进行连接
"""定义槽函数ClickButton"""
def ClickButton(self):
QMessageBox.information(self, "信息提示", "你确定了")
if __name__ == "__main__":
app = QApplication([])
window = Window()
window.show()
sys.exit(app.exec())
在上述代码中,定义了槽函数ClickButton(),表示按下按钮后要执行的代码;并使用button.clicked.connect()方法将clicked信号和ClickButton()槽函数进行连接。以此来设置按下该button后执行的代码。
运行程序后,弹出窗口如下:
点击button后,弹出对话框如下: