一、最小系统
框架
1.创建App对象(应用程序对象)
app = QApplication(sys.argv)
2.创建窗口
window = QWidget() - 调用 QWidget 这个类
3.设置窗口大小和位置
setGeometry(x, y, w, h) - x, y 窗口坐标;w,h 窗口大小
window.setGeometry(200, 100, 800, 600)
4.设置窗口标题(可选)
window.setWindowTitle('第一个窗口')
5.显示窗口
window.show()
6.启动程序
sys.exit(app.exec_())
实际使用时
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.create_ui()
self.setGeometry(200, 100, 800, 600)
self.setWindowTitle('图书管理系统')
self.show()
def create_ui(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
二、常用控件
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QLabel, QPushButton, QRadioButton, QCheckBox, QCommandLinkButton, QDialogButtonBox
from PyQt5.QtWidgets import QLineEdit, QTextEdit, QPlainTextEdit, QSpinBox, QDoubleSpinBox, QComboBox, QFontComboBox
from PyQt5.QtWidgets import QTimeEdit, QDateEdit, QDateTimeEdit, QDial, QSlider
from PyQt5.Qt import Qt
from datetime import date
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
# 设置全局按钮样式
self.setStyleSheet('QPushButton{color: #008000;background-color: #FFFF00;font-size: 20px;border: 1px solid #FF0000; border-radius: 8px;width: 100px; height: 40px;}')
self.create_ui()
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('常用控件')
self.show()
def create_ui(self):
# 0.设置背景颜色
bg_pa = QPalette()
# QColor(rgb颜色值)
bg_pa.setColor(self.backgroundRole(), QColor(81,44,78))
self.setPalette(bg_pa)
self.autoFillBackground()
# 1.标签
# QLabel(显示的文字, 父标签)
label1 = QLabel('用户名:', self)
label1.move(50, 10) # 默认在0,0的位置
# 2.按钮
btn1 = QPushButton('确定', self)
btn1.move(50, 50)
# css语法: 选择器{属性1: 属性值1; 属性2:属性值2;...}
# color - 字体颜色,对应的值:颜色单词、rbg(255, 0, 0)
# background-color - 背景颜色
# btn1.setStyleSheet('QPushButton{color: #008000;background-color: #FFFF00;font-size: 20px;border: 1px solid #FF0000; border-radius: 8px;width: 100px; height: 40px;}')
btn0 = QPushButton('取消', self)
btn0.move(0, 0)
btn2 = QRadioButton('男', self)
btn2.move(50, 100)
btn3 = QCheckBox('篮球', self)
btn3.move(50, 150)
btn4 = QCommandLinkButton('hello', 'hello world', self)
btn4.move(50, 200)
b1 = QDialogButtonBox.StandardButton.Ok
b2 = QDialogButtonBox.StandardButton.Cancel
b3 = QDialogButtonBox.StandardButton.Yes
btn5 = QDialogButtonBox(b3, self)
btn5.move(50, 250)
# 3.输入框
input1 = QLineEdit(self)
input1.move(150, 10)
input2 = QLineEdit('admin', self)
input2.move(150, 50)
# 修改输入框中的内容
input1.setText('zhangsan')
# 获取输入框中的内容
print(input1.text())
input3 = QTextEdit(self)
input3.move(50, 300)
input3.setText('hsshsshshhs')
# 设置成只读
input3.setReadOnly(True)
input4 = QPlainTextEdit(self)
input4.move(300, 10)
# 输入数值
input5 = QSpinBox(self)
input5.move(100, 100)
input5.setMinimum(10)
input5.setMaximum(20)
input5.setValue(15)
print(input5.value())
input6 = QDoubleSpinBox(self)
input6.move(100, 150)
# 下列列表
input7 = QComboBox(self)
input7.move(150, 200)
input7.addItems(['item1', 'item2', 'item3'])
print(input7.currentText()) # 获取当前选中的选项
input8 = QFontComboBox(self)
input8.move(350, 300)
input8.setCurrentIndex(9)
print(input8.currentFont()) # 获取当前选中的字体
label1.setFont(input8.currentFont())
# 日期选择
input9 = QDateEdit(date.today(), self)
input9.move(350, 350)
# 选择数值
input10 = QDial(self)
input10.move(350, 400)
input10.setMinimum(0)
input10.setMaximum(100)
# 滑块
input11 = QSlider(self)
input11.move(550, 300)
input11.setMaximum(-100)
input11.setMaximum(100)
input11.setValue(-100)
input11.setOrientation(Qt.Horizontal) # 设置方向为水平方向
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
ps:样式设置
css选择器:选择器{属性1:属性值1;属性2:属性值2…}
setStyleSheet | 说明 | 参数 |
---|---|---|
background-color | 背景颜色 | 颜色单词/rgb() |
color | 字体颜色 | 颜色单词/rgb() |
font-size | 字体大小 | XXpx |
border | 边框,宽度、样式、颜色 | 1px solid |
border-radius | 边框圆角大小 | 8px |
width | 宽度 | XXpx |
height | 高度 | XXpx |
font-weight | 字体粗细 | 100 ~ 900 |
三、绝对布局和垂直、水平盒子
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
from PyQt5.QtGui import QPalette, QColor
# *在一个布局结构中添加新的布局结构 box.addLayout(部件结构,弹簧数)
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.create_ui()
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('布局1')
self.show()
def create_ui(self):
# 1. 绝对定位 - 通过move方法直接设置标签的坐标(无法根据窗口大小变化而按比例变化)
# username = QLabel('用户名', self)
# username.move(300, 400)
# 2. QVBoxLayout 垂直盒子
# 1)创建布局对象并且和窗口进行关联
# 写法一
box = QVBoxLayout(self)
# 设置间距(无论窗口如何变化,间距不会变)
box.setContentsMargins(0, 0, 0, 0)
# 写法二
box = QVBoxLayout()
self.setLayout(box)
label1 = QLabel('用户名:')
label2 = QLabel('密 码:')
# 2) 将需要垂直布局的控件添加到布局盒子中
# 添加弹簧(用来控制控件间的距离):弹簧放的位置决定弹簧作用力的方向,N越大,作用力越大
box.addStretch(1)
box.addWidget(label1)
box.addWidget(label2)
box.addStretch(2)
# 3.QHBoxLayout 水平盒子
# 1)创建布局对象并关联
box = QHBoxlayout(self)
label1 = QLabel('用户名:')
label2 = QLabel('密 码:')
# 2)添加控件
box.addWidget(label1)
box.addWidget(label2)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
四、网格布局
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QHBoxLayout, QGridLayout, QPushButton, QLineEdit
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.create_ui()
self.setGeometry(200, 100, 800, 600)
self.setWindowTitle('布局2')
self.show()
def create_ui(self):
# 创建布局对象
box = QGridLayout(self)
# 普通添加
box.addwidget(控件,行号,列号)
# 合并添加
box.addwidget(控件,行号,列号,行合并数,列表合并数)
# 练习:计算器布局
input1 = QLineEdit('0', self)
box.addWidget(input1, 1, 1, 1, 4)
btn1 = QPushButton('Cls')
btn2 = QPushButton('Bck')
btn3 = QPushButton('Close')
btn4 = QPushButton('/')
btn5 = QPushButton('*')
btn6 = QPushButton('-')
btn7 = QPushButton('+')
btn8 = QPushButton('=')
btn9 = QPushButton('.')
box.addWidget(btn1, 2, 1)
box.addWidget(btn2, 2, 2)
box.addWidget(btn3, 2, 4)
box.addWidget(btn4, 3, 4)
box.addWidget(btn5, 4, 4)
box.addWidget(btn6, 5, 4)
box.addWidget(btn7, 6, 4)
box.addWidget(btn8, 6, 3)
box.addWidget(btn9, 6, 2)
btns = []
for x in range(11):
btn = QPushButton(str(x))
btns.append(btn)
box.addWidget(btns[0], 6, 1)
box.addWidget(btns[1], 5, 1)
box.addWidget(btns[2], 5, 2)
box.addWidget(btns[3], 5, 3)
box.addWidget(btns[4], 4, 1)
box.addWidget(btns[5], 4, 2)
box.addWidget(btns[6], 4, 3)
box.addWidget(btns[7], 3, 1)
box.addWidget(btns[8], 3, 2)
box.addWidget(btns[9], 3, 3)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
五、控件事件绑定
事件绑定三要素:xxx发生xx就做xx
事件源 发生 事件 就执行 某个操作(事件驱动程序)
绑定程序:事件源.事件.connect(操作对应的函数)
按钮点击事件
btn.clicked.connect(self.btn_action)
def btn_action(self):
print('按钮被点击')
输入框内容改变事件
self.input.textChang.connect(self.input_text_action)
# 输入框内容改变自动调用
def input_text_action(self, value):
print('输入框内容改变', value)
print(self.input1.text())
六、图片的使用
1.设置窗口图标
icon = QIcon('fiel/管理.png') #设置图标对象
self.setWindowICon(icon) # 设置图标对象
2.设置背景图片
1)设置
self.bg_label = QLabel(self) # 设置一个标签装图片
self.bg_label.setGeometry(0,0,800,450) # 设置标签大小
self.pix = QPixmap('fiel/pg.jpg') #设置图像
self.bg_label.setPixmap(self.pix)
2)当窗口缩放时,图片跟着缩放
def resizeEvent(self, a0) -> None: # 继承Qwitgets,窗口缩放时自动调用
w_size = self.size() # 获取最新窗口大小
# 对原图进行缩放(获得新的图片)
image = QImage('fiel/pg.jpg')
new_image = image.scaled(w_size.width(),w_size.hight())
pix = QPixmap.fromImage(new_image)
# 对显示图片的label进行缩放
self.bg_lable.setGeometry(0,0,w_size.width(),w_size.height())
self.bg_lable.setPixmap(pix)
3.显示网络图片
# 下载图片(download_image()是从网络下载图片的函数,返回值是二进制)
image_data = download_image()
# 使用网络图片数据创建图片对象
image = QImage.fromData(image_data)
# 对图片进行缩放
image = image.scaled(200, 200)
pix = QPixmap.fromImage(image)
# 显示图片
btn = QLabel(self)
btn.setGeometry(200, 100, 200, 200)
btn.setPixmap(pix)
七、菜单
如果想要在窗口上添加菜单,那么窗口的类型必须是QMainWindow或者是QMainWindow的子类
# 第一步,让窗口类继承QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.create_ui()
self.setGeometry(200, 100, 800, 600)
self.setWindowTitle('图书管理系统')
self.show()
def create_ui(self):
# 第二步:添加各种菜单
# 1.获取当前窗口上菜单栏
menu_bar = self.menuBar()
menu_bar.setNativeMenuBar(False) # mac电脑需要添加,否则菜单栏不显示
# 2.在菜单栏上添加菜单
file_menu = menu_bar.addMenu('&File') # 加不加 & 效果一样
edit_menu = menu_bar.addMenu('&Edit')
# 3.在菜单上添加选项
# 普通选项
fa1 = QAction('New Project', self) # 创建选项
fa1.triggered.connect(self.new_project) # 给选项绑定事件
# 带图标选项
fa2 = QAction(QIcon('files/打开文件夹.png'), 'Open', self)
fa2.triggered.connect(self.open_project)
fa2.setShortcut('ctrl+o') # 添加快捷键
# 将选项绑定在菜单
file_menu.addActions([fa1, fa2])
# 4.添加子菜单
file_p_menu = QMenu('File Projecties', self)
file_menu.addMenu(file_p_menu)
fpa1 = QAction('File Encoding', self)
fpa2 = QAction('Remove BOM', self)
fpa3 = QAction('Make File Read-Only', self)
file_p_menu.addActions([fpa1, fpa2, fpa3])
# 在窗口上点击鼠标右键的时候会被自动调用
def contextMenuEvent(self, event) -> None:
# 创建菜单对象
right_menu = QMenu(self)
# 在右键菜单上添加选项或者子菜单
a1 = QAction('Copy', self)
a2 = QAction('Paste', self)
a3 = QAction('Cut', self)
right_menu.addActions([a1, a2, a3])
# 点击右键菜单时让菜单显示在当前窗口鼠标所在的位置
right_menu.exec_(self.mapFromGlobal(event.pos()))
def new_project(self):
print('创建新的工程')
def open_project(self):
print('打开工程')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
八、对话框
1.消息类型对话框
消息框类型:information(报告)、question(询问)、warning(警告)、critical(报错)、about(关于)
QMessageBox.消息类型()
# 普通告知类型
QMessageBox.information(self, '对话框', '中午好!', QMessageBox.Ok )
# 询问类型
result = QMessageBox.question(self, '问题', '是否删除数据?', QMessageBox.Yes | QMessageBox.No)
print(result)
if result == Value.Yes:
print('Yes!')
else:
print('No!')
2.对话输入框
result = QInputDialog.getText(self, '', '请输入名字:')
print(result) # 打印出对话框输入的内容
3.其他框
QColorDialog.getColor() # 颜色
QFontDialog.getFont() # 字体框
QFileDialog.getOpenFileUrl() # 文件选择框