https://doc.qt.io/qt-5/qtwidgets-module.html
https://doc.qt.io/qt-5/qt.html#AlignmentFlag-enum
PyQt是Qt框架的Python语言实现,由Riverbank Computing开发,是最强大的GUI库之一。PyQt提供了一个设计良好的窗口控件集合,每一个PyQt控件都对应一个Qt控件。
PyQt5是由一系列Python模块组成,有超过620个类,6000个函数和方法,主要模块:
pip install pyqt5
pip install pyqt5-tools //pyqt5-tools为Qt Designer拖拽式的界面设计工具
import sys
from PyQt5.QtWidgets import QWidget,QApplication
app = QApplication(sys.argv)
window = QWidget()
window.resize(400, 200)
window.show()
sys.exit(app.exec_())
管理图形用户界面应用程序的控制流和主要设置 ,任何一个使用PyQt开发的图形用户界面应用程序,都存在一个QApplication对象
import sys
from PyQt5.QtWidgets import QWidget,QApplication
app = QApplication(sys.argv)
window = QWidget()
window.show()
# print('显示Qt相关信息',app.aboutQt())
# print('关闭所有窗口',app.closeAllWindows())
print('返回当前窗口对象',app.activeWindow())
print('获取桌面宽',app.desktop().width())
print('获取桌面高',app.desktop().height())
print('粘贴板对象',app.clipboard())
print('设置粘贴板文本',app.clipboard().setText('hello word'))
print('获取粘贴板文本',app.clipboard().text())
print('设置粘贴板文本',app.clipboard().mimeData().setText('hello word'))
print('获取粘贴板文本',app.clipboard().mimeData().text())
print('设置粘贴板html',app.clipboard().mimeData().setHtml('hello word
'))
print('获取粘贴板html',app.clipboard().mimeData().html())
print('设置粘贴板color',app.clipboard().mimeData().setColorData('#ffffff'))
print('获取粘贴板color',app.clipboard().mimeData().colorData())
# print('设置粘贴板url',app.clipboard().mimeData().setUrls())
# print('获取粘贴板url',app.clipboard().mimeData().urls())
# print('设置粘贴板img',app.clipboard().mimeData().setImageData())
# print('获取粘贴板img',app.clipboard().mimeData().imageData())
print('判断粘贴板中是否包含文本',app.clipboard().mimeData().hasText())
print('判断粘贴板中是否包含图片',app.clipboard().mimeData().hasImage())
print('判断粘贴板中是否包含html',app.clipboard().mimeData().hasHtml())
print('判断粘贴板中是否包含url',app.clipboard().mimeData().hasUrls())
print('判断粘贴板中是否包含颜色',app.clipboard().mimeData().hasColor())
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication
app = QApplication(sys.argv)
window = QWidget()
window.show()
print('设置工作区宽高',window.resize(400, 200))
print('设置工作区宽高,宽高都不可变',window.setFixedSize(400, 200))
print('设置工作区宽,且宽不可改变',window.setFixedWidth(400))
print('设置工作区高,且高不可改变',window.setFixedHeight(200))
print('同时设置工作区位置、宽高',window.setGeometry(0,0,420,200))
print('设置标题',window.setWindowTitle('我是标题')
print('窗口横坐标',window.x())
print('窗口纵坐标',window.y())
print('工作区域宽度',window.size().width())
print('工作区域高度',window.size().height())
print('工作区域宽度',window.width())
print('工作区域高度',window.height())
print('工作区横坐标',window.geometry().x())
print('工作区纵坐标',window.geometry().y())
print('工作区域宽度',window.geometry().width())
print('工作区域高度',window.geometry().height())
print('窗口横坐标',window.frameGeometry().x())
print('窗口纵坐标',window.frameGeometry().y())
print('窗口宽度',window.frameGeometry().width())
print('窗口高度',window.frameGeometry().height())
print('窗口宽度',window.frameSize().width())
print('窗口高度',window.frameSize().height())
print('设置窗口位置(窗口左上角)',window.move(0,0))
print('获得窗口左上角坐标:x',window.pos().x())
print('获得窗口左上角坐标:y',window.pos().y())
print('设置布局',window.setLayout(layout_object))) #QHBoxLayout水平布局、QVBoxLayout垂直布局、QGridLayout网格布局、QFormLayout表单布局、QStackedLayout栈式布局
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel
from PyQt5.QtGui import QFont
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
font = QFont()
font.setPointSize(18)
window.setFont(font)
label = QLabel('label文本',window)
label.move(30,40)
window.show()
sys.exit(app.exec_())
#设置窗口背景色
import sys
from PyQt5.QtWidgets import QWidget,QApplication
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
window.setObjectName('window')
window.setStyleSheet('#window{background:red}')
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication
from PyQt5.QtGui import QPalette
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
palette = QPalette()
palette.setColor(QPalette.Background, Qt.red)
window.setPalette(palette)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDialog,QPushButton,QVBoxLayout,QHBoxLayout,QFormLayout,QLabel,QLineEdit,QTextEdit,QComboBox,QRadioButton,QListView
from PyQt5.QtCore import Qt,QRegExp
from PyQt5.QtGui import QRegExpValidator,QIntValidator
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
show_btn = QPushButton('显示',window)
def onShowDialog():
dialog = QDialog(window)
dialog.setFixedWidth(600)
dialog.setWindowTitle('注册')
layout = QVBoxLayout()
h_layout = QHBoxLayout()
ok_button = QPushButton('确定')
cancel_button = QPushButton('取消')
ok_button.setFixedSize(80,30)
cancel_button.setFixedSize(80,30)
h_layout.addWidget(ok_button)
h_layout.addWidget(cancel_button)
ok_button.clicked.connect(lambda :print('点击 了确定'))
cancel_button.clicked.connect(lambda: dialog.close())
from_layout = QFormLayout()
name_label = QLabel('姓名:')
name_input = QLineEdit()
name_input.setFixedHeight(30)
name_input.setPlaceholderText('请输入姓名')
from_layout.addRow(name_label,name_input)
gender_label = QLabel('性别:')
gender_layout = QHBoxLayout()
male_radio = QRadioButton('男')
female_radio = QRadioButton('女')
gender_layout.addWidget(male_radio)
gender_layout.addWidget(female_radio)
gender_layout.addStretch(1)
gender_layout.insertSpacing(1,10)
from_layout.addRow(gender_label, gender_layout)
age_label = QLabel('年龄:')
age_input = QLineEdit()
# reg = QRegExpValidator(QRegExp(r'[0-9]+'))
# age_input.setValidator(reg)
age_input.setValidator(QIntValidator())
age_input.setFixedHeight(30)
age_input.setPlaceholderText('请输入年龄')
from_layout.addRow(age_label, age_input)
job_label = QLabel('职业:')
job_select = QComboBox()
job_select.setFixedHeight(30)
job_select.setStyleSheet('QComboBox QAbstractItemView::item{padding:5px 10px}')
job_select.setView(QListView())
job_select.addItems(['学生','医生','教师','警察'])
job_select.setPlaceholderText('请选择职业')
from_layout.addRow(job_label, job_select)
job_desc = QLabel('职业描述:')
desc_textarea = QTextEdit()
desc_textarea.setPlaceholderText('请输入职业描述')
from_layout.addRow(job_desc, desc_textarea)
layout.setSpacing(20)
layout.addLayout(from_layout)
h_layout.setContentsMargins(0,20,0,20)
layout.addLayout(h_layout)
dialog.setLayout(layout)
dialog.exec_()
show_btn.clicked.connect(onShowDialog)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QPushButton, QLabel, QListWidgetItem
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
show_btn = QPushButton('显示', window)
list_wideg = QListWidget(window)
label = QLabel('文本1')
list_wideg.addItem('文本1')
list_wideg.addItems(['文本2','文本3'])
item = QListWidgetItem()
item.setText('文本4')
list_wideg.addItem(item)
list_wideg.openPersistentEditor(list_wideg.item(1))
list_wideg.setFixedWidth(window.width())
list_wideg.move(0,40)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QHBoxLayout,QStackedWidget,QColorDialog,QFontDialog
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
layout = QHBoxLayout()
list_wideg = QListWidget()
list_wideg.setFixedWidth(200)
list_wideg.addItems(['颜色对话框','字体对话框'])
stacked_widget = QStackedWidget()
stacked_widget.addWidget(QColorDialog())
stacked_widget.addWidget(QFontDialog())
list_wideg.itemClicked.connect(lambda item:stacked_widget.setCurrentIndex(list_wideg.row(item)))
layout.addWidget(list_wideg)
layout.addWidget(stacked_widget)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget,QTableWidgetItem
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
table_widget = QTableWidget(window)
table_widget.setFixedSize(window.width(),window.height())
table_widget.setRowCount(4)
table_widget.setColumnCount(4)
table_widget.setHorizontalHeaderLabels(['姓名','性别','年龄','职业'])
table_widget.setItem(0,0,QTableWidgetItem('张三'))
table_widget.setItem(0,1,QTableWidgetItem('男'))
table_widget.setItem(0,2,QTableWidgetItem('18'))
table_widget.setItem(0,3,QTableWidgetItem('学生'))
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDockWidget,QListWidget
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
dock_widget = QDockWidget(window)
list_widget = QListWidget()
list_widget.addItems(['列表1','列表2'])
dock_widget.setWidget(list_widget)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCalendarWidget
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
calendar_widget = QCalendarWidget(window)
calendar_widget.setFixedSize(window.width(),window.height())
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTabWidget,QCalendarWidget,QColorDialog,QFontDialog
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
tab_widget = QTabWidget(window)
tab_widget.setFixedSize(window.width(),window.height())
calendar = QCalendarWidget()
tab_widget.addTab(calendar,'日历')
color = QColorDialog()
tab_widget.addTab(color,'颜色')
font = QFontDialog()
tab_widget.addTab(font,'字体')
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
label = QLabel('label文本', window)
label.move(200,200)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
top_label = QLabel('垂直靠上对齐')
bottom_label = QLabel('垂直靠下对齐')
v_center_label = QLabel('垂直居中对齐')
right_label = QLabel('水平右对齐')
left_label = QLabel('水平居左对齐')
center_label = QLabel('水平居中对齐')
justify_label1 = QLabel('水平两端对齐1')
justify_label2 = QLabel('水平两端对齐2')
# layout.addWidget(top_label,alignment=Qt.AlignTop)
# layout.addWidget(bottom_label,alignment=Qt.AlignBottom)
# layout.addWidget(v_center_label,alignment=Qt.AlignVCenter)
# layout.addWidget(right_label,alignment=Qt.AlignRight)
# layout.addWidget(left_label,alignment=Qt.AlignLeft)
# layout.addWidget(center_label,alignment=Qt.AlignCenter)
# layout.addWidget(justify_label1,alignment=Qt.AlignJustify)
# layout.addWidget(justify_label2,alignment=Qt.AlignJustify)
#上水平居中
layout.addWidget(right_label,alignment=Qt.AlignCenter | Qt.AlignTop)
'''
其他对齐方式
Qt.AlignAbsolute
Qt.AlignBaseline
Qt.AlignHCenter
Qt.AlignHorizontal_Mask
Qt.AlignLeading
Qt.AlignTrailing
Qt.AlignVertical_Mask
'''
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
stretch = QLabel('伸缩量')
stretch.setStyleSheet('QLabel{background:white}')
stretch1 = QLabel('伸缩量1')
stretch1.setStyleSheet('QLabel{background:yellow}')
stretch2 = QLabel('伸缩量2')
stretch2.setStyleSheet('QLabel{background:red}')
layout.addWidget(stretch)
layout.addStretch(2)
layout.addWidget(stretch1)
layout.addStretch(3)
layout.addWidget(stretch2)
layout.addStretch(1)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
stretch = QLabel('伸缩量')
stretch.setStyleSheet('QLabel{background:white}')
stretch1 = QLabel('伸缩量1')
stretch1.setStyleSheet('QLabel{background:yellow}')
stretch2 = QLabel('伸缩量2')
stretch2.setStyleSheet('QLabel{background:red}')
layout.addWidget(stretch)
layout.addSpacing(2)
layout.addWidget(stretch1)
layout.addSpacing(3)
layout.addWidget(stretch2)
layout.addSpacing(100)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
label = QLabel('文本')
label1 = QLabel('文本1')
layout.addWidget(label)
layout.addWidget(label1)
layout.removeWidget(label1) #删除文本1
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
label = QLabel('文本')
label1 = QLabel('文本1')
label2 = QLabel('文本2')
layout.addWidget(label)
layout.addWidget(label1)
layout.addWidget(label2)
window.setLayout(layout)
#清空layout中的所有对象
layout_index = list(range(layout.count()))
layout_index.reverse()# 倒序删除,避免影响布局顺序
for i in layout_index:
item = layout.itemAt(i)
layout.removeItem(item) #删除layout中的QLayoutItem对象
if item.widget():
item.widget().deleteLater()#删除item中的widget对象
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QGridLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QGridLayout()
grid_1 = QLabel('网格1')
grid_1.setStyleSheet('QLabel{background:red}')
grid_2 = QLabel('网格2')
grid_2.setStyleSheet('QLabel{background:yellow}')
grid_3 = QLabel('网格3')
grid_3.setStyleSheet('QLabel{background:blue}')
grid_4 = QLabel('网格4')
grid_4.setStyleSheet('QLabel{background:white}')
grid_5 = QLabel('网格5')
grid_5.setStyleSheet('QLabel{background:green}')
layout.addWidget(grid_1,0,0)
layout.addWidget(grid_2,0,1)
layout.addWidget(grid_3,1,0)
layout.addWidget(grid_4,1,1)
layout.addWidget(grid_5,2,0,2,2)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QFormLayout,QLineEdit
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QFormLayout()
label = QLabel('label')
field = QLineEdit()
field1 = QLineEdit()
layout.setSpacing(100)
layout.addRow(label,field)
layout.addRow(field1)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QFormLayout,QLineEdit,QPushButton
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QFormLayout()
label = QLabel('label')
field = QLineEdit()
layout.addRow(label,field)
layout.setWidget(1,QFormLayout.FieldRole,QPushButton('button'))
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QStackedLayout,QHBoxLayout,QPushButton,QStackedWidget
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
h_layout = QHBoxLayout()
btn = QPushButton('btn')
btn1 = QPushButton('btn1')
btn2 = QPushButton('btn2')
h_layout.addWidget(btn,alignment=Qt.AlignTop)
h_layout.addWidget(btn1,alignment=Qt.AlignTop)
h_layout.addWidget(btn2,alignment=Qt.AlignTop)
window.setLayout(h_layout)
layout = QStackedLayout()
label = QLabel('页面')
label1 = QLabel('页面1')
label2 = QLabel('页面2')
layout.addWidget(label)
layout.addWidget(label1)
layout.addWidget(label2)
def go_page():
btn_text = h_layout.sender().text()
print(btn_text)
if btn_text == 'btn':
layout.setCurrentIndex(0)
elif btn_text == 'btn1':
layout.setCurrentIndex(1)
elif btn_text == 'btn2':
layout.setCurrentWidget(label2)
#页面改变触发
layout.currentChanged.connect(lambda val: print('页面改变',val))
#页面移除触发
layout.widgetRemoved.connect(lambda val: print('页面移除',val))
btn.clicked[bool].connect(go_page)
btn1.clicked[bool].connect(go_page)
btn2.clicked[bool].connect(go_page)
h_layout.addLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QSplitter,QHBoxLayout,QLabel,QFrame
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
top_left = QFrame()
top_left.setFrameShape(QFrame.StyledPanel)
top_right = QFrame()
top_right.setFrameShape(QFrame.StyledPanel)
h = QSplitter(Qt.Horizontal)
h.addWidget(top_left)
h.addWidget(top_right)
bottom = QFrame()
bottom.setFrameShape(QFrame.StyledPanel)
v = QSplitter(Qt.Vertical)
v.addWidget(h)
v.addWidget(bottom)
layout.addWidget(v)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QGridLayout,QHBoxLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QGridLayout()
h_layout = QHBoxLayout()
h_layout.addWidget(QLabel('水平布局'))
grid_1 = QLabel('网格1')
grid_1.setStyleSheet('QLabel{background:red}')
grid_2 = QLabel('网格2')
grid_2.setStyleSheet('QLabel{background:yellow}')
grid_3 = QLabel('网格3')
grid_3.setStyleSheet('QLabel{background:blue}')
grid_4 = QLabel('网格4')
grid_4.setStyleSheet('QLabel{background:white}')
grid_5 = QLabel('网格5')
grid_5.setStyleSheet('QLabel{background:green}')
layout.addWidget(grid_1,0,0)
layout.addWidget(grid_2,0,1)
layout.addWidget(grid_3,1,0)
layout.addWidget(grid_4,1,1)
layout.addWidget(grid_5,2,0,2,2)
layout.addLayout(h_layout,2,0)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
用于显示不可编辑的文本或图片、也可以放置一个GIF动画或者设置超链接、富文本、占位符等,Qlabel(text,QWidget);设值的方法,必有对应获取的方法,如:setText(text)设置t文本内容,对应text()获取文本内容
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
label = QLabel('文本对齐方式,同addWidget中alignment参数')
label.setAlignment(Qt.AlignTop)
layout.addWidget(label)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QHBoxLayout
from PyQt5.QtGui import QPixmap
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QHBoxLayout()
label = QLabel()
pixmap = QPixmap('./img/tengxun.png')
label.setPixmap(pixmap)
layout.addWidget(label)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QToolTip
from PyQt5.QtGui import QFont
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
label = QLabel('label',window)
QToolTip.setFont(QFont('SansSerif', 20))
label.setToolTip('我是提示信息')
label.move(0,0)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QFormLayout,QLineEdit
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
layout = QFormLayout()
label = QLabel('label(&N)')
line_edit = QLineEdit()
label.setBuddy(line_edit)
layout.addRow(label,line_edit)
label1 = QLabel('label1(&P)')
line_edit1 = QLineEdit()
label1.setBuddy(line_edit1)
layout.addRow(label1,line_edit1)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
label = QLabel('百度链接:跳转百度',window)
label.setOpenExternalLinks(True)
print(label.openExternalLinks())
label.linkHovered.connect(lambda :print('hover'))
#setOpenExternalLinks(False) 触发linkActivated
label.linkActivated.connect(lambda :print('click'))
label.move(0,0)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
label = QLabel('百度链接:百度',window)
label.mouseDoubleClickEvent = lambda event:print(event)
label.move(0,0)
window.show()
sys.exit(app.exec_())
#使用信号/槽的方式重写event事件
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLabel
from PyQt5.QtCore import pyqtSignal
class MyQLabel(QLabel):
# 自定义单击信号
clicked = pyqtSignal(object)
# 自定义双击信号
doubleClicked = pyqtSignal(object)
def __int__(self):
super().__init__()
# 重写鼠标单击事件
def mousePressEvent(self, event): # 单击
self.clicked.emit(event)
# 重写鼠标双击事件
def mouseDoubleClickEvent(self, event): # 双击
self.doubleClicked.emit(event)
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
label = MyQLabel('百度链接:百度',window)
label.clicked.connect(lambda event:print(label.text()))
label.move(0,0)
window.show()
sys.exit(app.exec_())
QPushButton小部件提供了一个命令按钮,常用于用户之间的交互,如:点击、双击、form表单提交等,QPushButton(icon,text,QWidget);设值的方法,必有对应获取的方法,如:setText(text)设置t文本内容,对应text()获取文本内容
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QPushButton
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
button = QPushButton('按钮',window)
button.clicked.connect(lambda :print('点击')) #内置信号/槽,event事件各控件大同小异,可看源码有哪些event事件
button.move(0,0)
window.show()
sys.exit(app.exec_())
QTextEdit控件是一个支持多行输入的输入框,支持HTML进行格式的设置;QTextEdit(text,QWidget);设值的方法,必有对应获取的方法,如:setPlainText(text)设置t文本内容,对应toPlainText()获取文本内容
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QTextEdit
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
text_edit = QTextEdit(window)
text_edit.setText('初始化文本')
text_edit.append('append文本')
text_edit.append('append Html')
text_edit.insertPlainText('插入文本')
text_edit.insertHtml('insert Html')
'''
内置信号/槽,event事件各控件大同小异,可看源码有哪些event事件
textChanged:文本内容发生改变时,发射该信号;
selectionChanged:选中内容发生改变时,发射该信号;
cursorPositionChanged:光标位置发生改变时,发射该信号;
currentCharFormatChanged:当前字符格式发生改变时,发射该信号;
copyAvailable:复制可用时,发射该信号;
redoAvailable:重做可用时,发射该信号;
undoAvailable:撤销可用时,发射该信号。
'''
text_edit.selectionChanged.connect(lambda :print('文本选择'))
text_edit.textChanged.connect(lambda :print('文本改变'))
window.show()
sys.exit(app.exec_())
QLineEdit控件是一个输入框,QLineEdit(text,QWidget);设值的方法,必有对应获取的方法,如:setText(text)设置t文本内容,对应text()获取文本内容
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QLineEdit
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
line_edit = QLineEdit('哈哈哈',window)
line_edit.selectionChanged.connect(lambda :print('文本选择'))
line_edit.textChanged.connect(lambda :print('文本改变'))
line_edit.editingFinished.connect(lambda :print('文本结束'))
window.show()
sys.exit(app.exec_())
QDateEdit控件是一个日期控件,QDateEdit(QDate,QWidget);设值的方法,必有对应获取的方法,如:setDate(QDate)设置日期,对应date()获取日期
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QDateEdit
from PyQt5.QtCore import QDate
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
date_edit = QDateEdit(QDate.currentDate(),window)
date_edit.setDisplayFormat('yyyy/MM/dd')
date_edit.setCalendarPopup(True)
date_edit.setMaximumDate(QDate.currentDate().addDays(29))
date_edit.setMinimumDate(QDate.currentDate().addDays(0))
def getDateInfo():
print('当前日期:', date_edit.date())
print('当前时间:', date_edit.dateTime())
print('最大日期:', date_edit.maximumDate())
print('最小日期:', date_edit.minimumDate())
print('最小时间:', date_edit.minimumDateTime())
print('最大时间:', date_edit.maximumDateTime())
date_edit.dateChanged.connect(getDateInfo)
window.show()
sys.exit(app.exec_())
QTimeEdit控件是一个时间控件,QTimeEdit(QTime,QWidget);设值的方法,必有对应获取的方法,如:setTime(QTime)设置时间,对应time()获取时间
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QTimeEdit
from PyQt5.QtCore import QTime
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
time_edit = QTimeEdit(QTime.currentTime(),window)
time_edit.setDisplayFormat('hh:mm:ss')
def getTimeInfo():
print('当前时间:', time_edit.time())
print('最小时间:', time_edit.minimumTime())
print('最大时间:', time_edit.maximumTime())
time_edit.timeChanged.connect(getTimeInfo)
window.show()
sys.exit(app.exec_())
QDateTimeEdit控件是一个日期时间控件,QTimeEdit(QDateTime,QWidget);设值的方法,必有对应获取的方法,如:setDateTime(QDateTime)设置时间,对应dateTime()获取时间
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QDateTimeEdit
from PyQt5.QtCore import QDateTime
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
date_time_edit = QDateTimeEdit(window)
date_time_edit.setDateTime(QDateTime.currentDateTime())
date_time_edit.setCalendarPopup(True)
date_time_edit.timeChanged.connect(lambda :print('时间改变'))
date_time_edit.dateChanged.connect(lambda :print('日期改变'))
date_time_edit.dateTimeChanged.connect(lambda :print('日期时间改变'))
window.show()
sys.exit(app.exec_())
QComboBox控件是一个下拉选择框,QComboBox(QWidget);设值的方法,必有对应获取的方法,如:setCurrentText(text)设置当前选中文本,对应currentText()获取当前选中文本
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QComboBox,QListView
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
select = QComboBox(window)
select.setMinimumSize(200,30)
select.setStyleSheet('QComboBox QAbstractItemView::item{padding:5px 10px}')
select.setView(QListView())
select.addItem('选项一','option1')
select.addItem('选项二','option2')
select.addItems(['选项三','选项四'])
select.setItemData(2,'option3')
select.setItemData(3,'option4')
select.setCurrentText('选项二')
#用户选中某个下拉选项
select.activated.connect(lambda :print('asda'))
#当前选项index发生改变
select.currentIndexChanged.connect(lambda :print('index改变'))
#当前选项text发生改变
select.currentTextChanged.connect(lambda :print('text改变'))
#当选中已经选中的一个下拉项时
select.highlighted.connect(lambda :print('该项已选择'))
window.show()
sys.exit(app.exec_())
QCheckBox控件是一个多选框,QCheckBox(text,QWidget);设值的方法,必有对应获取的方法,如:setText(text)设置文本,对应text()获取文本
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QCheckBox
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
check_box1 = QCheckBox('复选框一',window)
check_box2 = QCheckBox('复选框二',window)
check_box2.move(0,20)
check_box3 = QCheckBox('复选框三',window)
check_box3.move(0,40)
check_box4 = QCheckBox('复选框四',window)
check_box4.move(0,60)
check_box1.clicked.connect(lambda :print('点击'))
check_box1.pressed.connect(lambda :print('长按'))
check_box1.released.connect(lambda :print('长按释放'))
check_box1.toggled.connect(lambda checked:print(checked))
window.show()
sys.exit(app.exec_())
QRadioButton控件是一个单选框,QRadioButton(text,QWidget);设值的方法,必有对应获取的方法,如:setText(text)设置文本,对应text()获取文本
import sys
from PyQt5.QtWidgets import QWidget,QApplication,QRadioButton
app = QApplication(sys.argv)
window = QWidget()
window.resize(800,600)
radio_box1 = QRadioButton('单选框一',window)
radio_box2 = QRadioButton('单选框二',window)
radio_box2.move(0,20)
radio_box3 = QRadioButton('单选框三',window)
radio_box3.move(0,40)
radio_box4 = QRadioButton('单选框四',window)
radio_box4.move(0,60)
radio_box1.clicked.connect(lambda :print('点击'))
radio_box1.pressed.connect(lambda :print('长按'))
radio_box1.released.connect(lambda :print('长按释放'))
radio_box1.toggled.connect(lambda checked:print(checked))
window.show()
sys.exit(app.exec_())
QGroupBox控件是一个分组框,QGroupBox(title,QWidget);设值的方法,必有对应获取的方法,如:setTitle(text)设置标题,对应title()获取标题
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QGroupBox, QCheckBox, QHBoxLayout
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
group_box = QGroupBox('第一组复选框', window)
group_box.setFixedSize(400, 200)
group_box.setContentsMargins(10, 40, 10, 10)
group_box.set
layout = QHBoxLayout()
check_box1 = QCheckBox('复选框1')
check_box2 = QCheckBox('复选框2')
check_box3 = QCheckBox('复选框3')
layout.addWidget(check_box1, alignment=Qt.AlignTop)
layout.addWidget(check_box2, alignment=Qt.AlignTop)
layout.addWidget(check_box3, alignment=Qt.AlignTop)
group_box.setLayout(layout)
group_box.clicked.connect(lambda :print('点击'))
group_box.toggled.connect(lambda :print('状态发生改变'))
group_box_2 = QGroupBox('第二组复选框', window)
group_box_2.setFixedSize(400, 200)
group_box_2.move(400,0)
group_box_2.setContentsMargins(10, 40, 10, 10)
layout2 = QHBoxLayout()
check_box2_1 = QCheckBox('复选框1')
check_box2_2 = QCheckBox('复选框2')
check_box2_3 = QCheckBox('复选框3')
layout2.addWidget(check_box2_1, alignment=Qt.AlignTop)
layout2.addWidget(check_box2_2, alignment=Qt.AlignTop)
layout2.addWidget(check_box2_3, alignment=Qt.AlignTop)
group_box_2.setLayout(layout2)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox,QGroupBox,QPushButton,QVBoxLayout
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
group_box = QGroupBox('消息提示框',window)
group_box.setFixedWidth(400)
layout = QVBoxLayout()
warning_btn = QPushButton('警告框')
info_btn = QPushButton('信息框')
confirm_btn= QPushButton('确认框')
err_btn = QPushButton('错误框')
about_btn = QPushButton('关于对话框')
layout.addWidget(warning_btn,alignment=Qt.AlignTop)
layout.addWidget(info_btn,alignment=Qt.AlignTop)
layout.addWidget(confirm_btn,alignment=Qt.AlignTop)
layout.addWidget(err_btn,alignment=Qt.AlignTop)
layout.addWidget(about_btn,alignment=Qt.AlignTop)
def showWarningMessage():
btn = QMessageBox.warning(window, '警告框', '警告信息', QMessageBox.Ok | QMessageBox.Cancel,QMessageBox.NoButton)
if btn == QMessageBox.Ok:
print('选择了OK操作')
elif btn == QMessageBox.Cancel:
print('选择了取消操作')
warning_btn.clicked.connect(showWarningMessage)
def showInfoMessage():
btn = QMessageBox.information(window, '信息框', '信息',QMessageBox.Yes | QMessageBox.No)
if btn == QMessageBox.Yes:
print('选择了yes操作')
elif btn == QMessageBox.No:
print('选择了no操作')
info_btn.clicked.connect(showInfoMessage)
def showConfrimMessage():
btn = QMessageBox.question(window, '确认框', '确认信息',QMessageBox.Ok | QMessageBox.Reset)
if btn == QMessageBox.Ok:
print('选择了终止操作')
elif btn == QMessageBox.Reset:
print('选择重置操作')
confirm_btn.clicked.connect(showConfrimMessage)
def showErrMessage():
btn = QMessageBox.critical(window, '错误框', '错误信息',QMessageBox.Abort | QMessageBox.Retry)
if btn == QMessageBox.Abort:
print('选择了终止操作')
elif btn == QMessageBox.Retry:
print('选择重试操作')
err_btn.clicked.connect(showErrMessage)
def showAboutMessage():
btn = QMessageBox.about(window, '自定义', '错误信息')
if btn == QMessageBox.Abort:
print('选择了终止操作')
elif btn == QMessageBox.Retry:
print('选择重试操作')
about_btn.clicked.connect(showAboutMessage)
group_box.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QGroupBox, QPushButton, QVBoxLayout
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
group_box = QGroupBox('消息提示框', window)
group_box.setFixedWidth(400)
layout = QVBoxLayout()
warning_btn = QPushButton('警告框')
custom_btn = QPushButton('自定义框')
layout.addWidget(warning_btn, alignment=Qt.AlignTop)
layout.addWidget(custom_btn, alignment=Qt.AlignTop)
def showWarningMessage():
message_box = QMessageBox()
message_box.setIcon(QMessageBox.Warning)
message_box.setWindowTitle('警告')
message_box.setText('警告信息')
message_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
message_box.setDetailedText('警告详情')
btn = message_box.exec_()
if btn == QMessageBox.Ok:
print('选择了确定操作')
elif btn == QMessageBox.Cancel:
print('选择了取消操作')
warning_btn.clicked.connect(showWarningMessage)
def showInfoMessage():
message_box = QMessageBox()
message_box.setIcon(QMessageBox.Information)
message_box.setWindowTitle('信息')
message_box.setText('信息')
message_box.addButton('确定',QMessageBox.AcceptRole)
message_box.addButton('取消', QMessageBox.RejectRole)
message_box.addButton(QMessageBox.Ok)
btn = message_box.exec_()
if btn == QMessageBox.AcceptRole or btn == QMessageBox.Ok :
print('选择了确定操作')
elif btn == QMessageBox.RejectRole:
print('选择了取消操作')
custom_btn.clicked.connect(showInfoMessage)
group_box.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox, QPushButton, QErrorMessage
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
click_btn = QPushButton('错误信息框',window)
def showErrorMessage():
message_box = QErrorMessage()
message_box.showMessage('错误信息')
message_box.setWindowTitle('标题')
btn = message_box.exec_()
if btn == QMessageBox.Information:
print('选择了确定操作')
click_btn.clicked.connect(showErrorMessage)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QColorDialog,QDialog
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
click_btn = QPushButton('颜色框',window)
# def showColorDialog():
# color_dialog = QColorDialog()
# color_dialog.setWindowTitle('颜色框标题') #设置标题
# # color_dialog.setWindowIcon()#设置ICON
# # color_dialog.setCustomColor(0, Qt.red) #设置自定颜色
# print('获取自定义颜色:',color_dialog.customColor(0).name())
# btn = color_dialog.exec_()
# current_color = color_dialog.currentColor()
# print('当前选中颜色值:', current_color.name())
# print('当前选中颜色值RGB:', f'{current_color.red()},{current_color.green()},{current_color.blue()}')
def showColorDialog():
color = QColorDialog.getColor()
print(color)
click_btn.clicked.connect(showColorDialog)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QFontDialog,QPushButton
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
click_btn = QPushButton('选择字体',window)
# def showFontDialog():
# font_dialog = QFontDialog()
# font_dialog.setWindowTitle('标题')
# btn = font_dialog.exec_()
# curret_font = font_dialog.currentFont()
# print('当前选中字体',curret_font)
def showFontDialog():
font = QFontDialog.getFont()
print(font)
click_btn.clicked.connect(showFontDialog)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QFileDialog,QPushButton
import os
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
file_btn = QPushButton('选择文件',window)
file_multi_btn = QPushButton('多选文件',window)
file_multi_btn.move(0,40)
dir_btn = QPushButton('选择文件夹',window)
dir_btn.move(0,80)
save_btn = QPushButton('保存文件',window)
save_btn.move(0,120)
custom_btn = QPushButton('自定义',window)
custom_btn.move(0,160)
def onFileChoose():
filename, filetype = QFileDialog.getOpenFileName(parent=window,
caption='选择文件',
directory=os.getcwd(),
filter='Text Files(*.txt);;All Files(*)')
print(filename, filetype)
file_btn.clicked.connect(onFileChoose)
def onFileMultiChoose():
filename, filetype = QFileDialog.getOpenFileNames(parent=window,
caption='多选文件',
directory=os.getcwd(),
filter='Text Files(*.txt);;All Files(*)')
print(filename, filetype)
file_multi_btn.clicked.connect(onFileMultiChoose)
def onDirChoose():
dir = QFileDialog.getExistingDirectory(parent=window,
caption='选择文件夹',
directory=os.getcwd(),
filter='PDF Files (*.pdf);;Text Files (*.txt);;All Files (*.*)')
print(dir)
dir_btn.clicked.connect(onDirChoose)
def onFileSave():
filename, filetype = QFileDialog.getSaveFileName(parent=window,
caption='保存文件',
directory=os.getcwd())
print(filename, filetype)
print(dir)
save_btn.clicked.connect(onFileSave)
dialog = QFileDialog(window)
def onShowDialog():
dialog.setAcceptMode(QFileDialog.AcceptOpen)
dialog.exec_()
custom_btn.clicked.connect(onShowDialog)
def selectFn():
print('文件名:',dialog.selectedFiles())
dialog.fileSelected.connect(selectFn)
window.show()
sys.exit(app.exec_())
'''
QFileDialog.getOpenFileName(parent,caption, directory, filter):选择本地文件,控件父级:parent、标题:caption、路径:directory、文件类型:filter
QFileDialog.getOpenFileNames(parent,caption, directory, filter):选择多个本地文件路径
QFileDialog.getExistingDirectory(parent,caption, directory):选择文件夹路径
QFileDialog.getSaveFileName(parent,caption, directory, filter):本地文件保存对话框
QFileDialog.getOpenFileUrl(parent,caption, directory, filter):选择远程文件;
QFileDialog.getOpenFileUrls(parent,caption, directory, filter):选择多个远程文件;
QFileDialog.getExistingDirectoryUrl(parent,caption, directory):选择远程文件夹
QFileDialog.getSaveFileUrl(parent,caption, directory, filter):远程文件保存;
QFileDialog().setAcceptMode(mode): 设置是对话框类型,选择:QFileDialog.AcceptOpen、保存:QFileDialog.AcceptSave
QFileDialog().setViewMode(mode): 设置视图模式,QFileDialog.Detail: 显示文件和目录的名称和图标以及更多的信息,比如文件的大小和修改日期;QFileDialog.List: 显示文件和目录的名称和图标)
QFileDialog().setFilter(str):设置文件类型过滤器,只有包含在括号内的内容才会作为过滤器,后缀之间由空格或者分号分隔
QFileDialog().setFileMode(mode): 设置文件模式,任意文件:QFileDialog.AnyFile、 已存在的文件:QFileDialog.ExistingFile、 文件夹:QFileDialog.Directory、多个文件:QFileDialog.ExistingFiles、只能为目录:QFileDialog.DirectoryOnly
QFileDialog().setLabelText(): 设置指定角色的标签名称,QFileDialog.LookIn、QFileDialog.FileName、QFileDialog.FileType、QFileDialog.Accept、QFileDialog.Reject
QFileDialog().setDefaultSuffix(str):设置默认后缀
QFileDialog().selectedFiles():返回选择的文件名称
QFileDialog().setCancelButtonText(text):设置取消btn文本
QFileDialog().setOkButtonText(text):设置确认btn文本
''''
'''
常用信号:
dirEntered: 当用户进入一个目录时,该信号被发射;
fileHighlighted: 当用户高亮显示一个文件时,该信号被发射;
fileSelected: 当用户选择一个文件时,该信号被发射;
filesSelected: 当用户在ExistingFiles模式下选择一个或多个文件时,该信号被发射;
filterSelected: 当用户选择一个过滤器时,该信号被发射;
'''
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QInputDialog, QPushButton
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
int_btn = QPushButton('整数',window)
item_btn = QPushButton('选项',window)
item_btn.move(0,40)
int_btn = QPushButton('整数',window)
item_btn = QPushButton('选项',window)
item_btn.move(0,40)
customn_int_btn = QPushButton('自定义整数',window)
customn_int_btn.move(0,80)
def onInputInt():
int, bool = QInputDialog.getInt(window, '输入框标题', '这是提示信息\n\n请输入整数:', 37, -10000, 10000, 2)
print(int, bool)
int_btn.clicked.connect(onInputInt)
def onInputItem():
list_ =['选项一','选项二','选项三']
item, bool = QInputDialog.getItem(window, '文本', '请选择',list_,1, True)
print(bool, item)
item_btn.clicked.connect(onInputItem)
def onCustomInput():
dialog = QInputDialog()
dialog.setInputMode(QInputDialog.IntInput)
dialog.setLabelText('自定义')
dialog.setOkButtonText('确定')
dialog.setCancelButtonText('取消')
dialog.exec_()
customn_int_btn.clicked.connect(onCustomInput)
window.show()
sys.exit(app.exec_())
'''
QInputDialog.getInt(parent,title,label,value,min,max,step):输入整数
QInputDialog.getDouble(parent,title,label,value,min,max,step):输入小数
QInputDialog.getText(parent,title,label,text):输入文本
QInputDialog.getMultiLineText(parent,title,label,text):多行文本
QInputDialog.getItem(parent,title,label,item,selectIndex): 多选
QInputDialog().setOkButtonText(text):确定button文本
QInputDialog().setCancelButtonText(text):取消button文本
'''
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QProgressDialog, QPushButton
from PyQt5.QtCore import Qt
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
progress_btn = QPushButton('进度条',window)
def onShowProgress():
progress = QProgressDialog()
progress.setLabelText('进度条')
progress.setCancelButtonText('取消')
progress.setRange(0,100)
progress.setValue(90)
progress.exec_()
progress_btn.clicked.connect(onShowProgress)
window.show()
sys.exit(app.exec_())
'''
setLabelText(text):设置对话框中标签显示文本
setCancelButtonText(text):设置取消按钮的显示文本
setMinimumDuration(int):设置最小持续时间
setWindowModality(Qt.WindowModality): 设置窗口的模态属性
setRange(min,max): 设置取值范围;
setMinimum(min): 设置最小值;
setMaximum(max): 设置最大值;
setValue(value): 设置当前的进度值,在最小值和最大值之间(包括最小最大值);
wasCanceled(): 判断是否按下了取消键;
setAutoReset(bool): 设置是否自动重置;
setAutoClose(bool): 设置是否自动关闭;
open(receiver, member): 打开对话框,并将其cancelled()信号连接到receiver和member指定的插槽,关闭对话框后,信号将从插槽中断开。
'''
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QWizard, QWizardPage,QPushButton
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
show_btn = QPushButton('向导',window)
def onShowWizard():
wizard = QWizard()
page1 = QWizardPage()
page1.setTitle('页面1')
page2 = QWizardPage()
page2.setTitle('页面2')
page3 = QWizardPage()
page3.setTitle('页面3')
page1_id = wizard.addPage(page1)
page2_id = wizard.addPage(page2)
page2_id = wizard.addPage(page3)
wizard.setButtonText(QWizard.BackButton,'返回')
wizard.setButtonText(QWizard.FinishButton, '确定')
wizard.setButtonText(QWizard.CommitButton, '提交')
wizard.setButtonText(QWizard.NextButton,'下一步')
wizard.setButtonText(QWizard.CancelButton, '取消')
wizard.exec_()
show_btn.clicked.connect(onShowWizard)
window.show()
sys.exit(app.exec_())
'''
addPage(QWizardPage):将给定的页面添加到向导,并返回页面的ID
setPage(id,QWizardPage):在指定位置设置一个页面
removePage(id):移除指定位置的页面
page(id):得到指定位置的页面
currentPage():获得当前页面
setWizardStyle(QWizard.WizardPixmap):设置向导风格,共有五种设置[ClassicStyle,ModernStyle, MacStyle, AeroStyle, NStyles]
setOption():如果参数on为True,则将给定选项设置为启用,否则清除该给定选项
setOptions():设置给定选项
testOption():如果已启用给定选项,则返回True,否则返回False
setButtonText(QWizard.WizardButton,text):设置按钮上显示的文字
setPixmap():设置指定角色的位图,其取值见WizardPixmap取值
setTitleFormat(Qt.TextFormat):设置主标题的文本格式
setSubTitleFormat(Qt.TextFormat):设置子标题的文本格式
next():前进到下一页
back():返回到上一页
restart():在开始页面重新启动向导。显示向导时,将自动调用此功能
'''
QMenu菜单控件,需要依赖能创建菜单的控件,如:QPushButton
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMenu,QPushButton,QAction,QActionGroup
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
menu_btn = QPushButton('菜单',window)
menu = QMenu(window)
first_action = menu.addAction('选项1')
two_action = menu.addAction('选项2')
menu.addAction('选项3')
child_menu = menu.addMenu('子菜单')
child_menu.addAction('选项1')
child_menu.addAction('选项2')
child_menu.addAction('选项3')
child_menu1 = QMenu(window)
child_menu1.addAction('选项1')
child_menu1.addAction('选项2')
child_menu1.addAction('选项3')
menu.addSeparator()
menu.addMenu(child_menu1)
child_menu2 = QMenu(window)
child_menu2.addAction('插入选项1')
child_menu2.addAction('插入选项2')
child_menu2.addAction('插入选项3')
menu.insertSeparator(first_action)
menu.insertMenu(first_action,child_menu2)
menu_btn.setMenu(menu)
window.show()
sys.exit(app.exec_())
QStatusBar窗口底部状态栏,适用于可以设置状态栏的窗口,如:QMainWindow
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QStatusBar,QLabel
app = QApplication(sys.argv)
window = QMainWindow()
window.resize(800, 600)
status_bar = QStatusBar(window)
status_bar.addWidget(QLabel('文本'))
status_bar.addPermanentWidget(QLabel('永久文本'))
status_bar.showMessage('临时消息',10)
window.setStatusBar(status_bar)
window.show()
sys.exit(app.exec_())
QMenuBar菜单栏,适用于可以设置菜单栏的窗口,如:QMainWindow
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu,QAction,QMenuBar
app = QApplication(sys.argv)
window = QMainWindow()
window.resize(800, 600)
menu_bar = QMenuBar()
menu = QMenu('文件')
menu.addAction('打开')
menu.addAction('添加')
menu.addAction('保存')
menu.addAction('删除')
menu_bar.addMenu(menu)
action = QAction('编辑')
menu_bar.addAction(action)
window.setMenuBar(menu_bar)
window.show()
sys.exit(app.exec_())
QTabBar可切换的tab,设值的方法,必有对应获取的方法,如:setTitle(text)设置标题,对应title()获取标题
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTabBar,QStackedLayout,QVBoxLayout,QLabel,QAction
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
tab_bar = QTabBar()
tab1 = tab_bar.addTab('tab1')
tab2 = tab_bar.addTab('tab2')
tab3 = tab_bar.addTab('tab3')
page1 = QWidget(window)
page2 = QWidget(window)
page3 = QWidget(window)
layout = QStackedLayout()
layout.addWidget(page1)
layout.addWidget(page2)
layout.addWidget(page3)
win_layout = QVBoxLayout()
win_layout.addWidget(tab_bar)
win_layout.addLayout(layout)
QLabel('页面1',page1)
QLabel('页面2',page2)
QLabel('页面3',page3)
layout.setCurrentIndex(0)
tab_bar.currentChanged.connect(layout.setCurrentIndex)
window.setLayout(win_layout)
window.show()
sys.exit(app.exec_())
QFrame边框控件,大部分控件都有以下方法来设置边框
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QFrame,QVBoxLayout
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
layout = QVBoxLayout()
frame1 = QFrame(window)
frame1.setFrameShape(QFrame.Box)
layout.addWidget(frame1)
frame2 = QFrame(window)
frame2.setFrameShape(QFrame.HLine)
frame2.setLineWidth(3)
layout.addWidget(frame2)
frame3 = QFrame(window)
frame3.setFrameShape(QFrame.Panel)
frame3.setFrameShadow(QFrame.Raised)
layout.addWidget(frame3)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout,QScrollBar,QLabel
app = QApplication(sys.argv)
window = QWidget()
window.resize(800, 600)
layout = QHBoxLayout()
scroll_bar = QScrollBar()
layout.addWidget(scroll_bar)
label = QLabel('文字')
layout.addWidget(label)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
pip install pyqt5
pip install pyqt5-tools
pip install pyqt5designer
$ProjectFileDir$
-o $FileNameWithoutExtension$.py $FileName$
$FileDir$
$FileName$ -o $FileNameWithoutExtension$_rc.py
$FileDir$
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from untitled import Ui_Form
class MyMainForm(QWidget, Ui_Form):
def __init__(self, parent=None):
super(MyMainForm, self).__init__(parent)
self.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
myWin = MyMainForm()
myWin.show()
sys.exit(app.exec_())