文章目录
对话框
标准对话框
QInputDialog
可以获取int、doule、text、item的输入;
QFileDialog
可以获取文件信息:openFileName、openFileNames、openSaveFile、openExistingDirectory
QFontDialog
选择字体
QColorDialog
选择颜色
QMessageBox
可以给出各种对话框
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGroupBox, QPushButton, QVBoxLayout, QWizard, QWizardPage, \
QFormLayout, QLineEdit, QDialog, QInputDialog, QColorDialog, QFontDialog, QFileDialog, QMessageBox
import os
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.__buildUI()
self.__setWindow()
# ================== 功能函数 ==================
def __setWindow(self):
self.resize(400, 480)
def __buildUI(self):
form = QFormLayout(self)
form.addRow('getInt', QPushButton('getInt', clicked=self.__getInt))
form.addRow('getDouble', QPushButton('getDouble', clicked=self.__getDouble))
form.addRow('getText', QPushButton('getText', clicked=self.__getText))
form.addRow('getItem', QPushButton('getItem', clicked=self.__getItem))
form.addRow('getColor', QPushButton('getColor', clicked=self.__getColor))
form.addRow('getFont', QPushButton('getFont', clicked=self.__getFont))
form.addRow('getExistingDirectory', QPushButton('getExistingDirectory', clicked=self.__getExistingDirectory))
form.addRow('getOpenFileName', QPushButton('getOpenFileName', clicked=self.__getOpenFileName))
form.addRow('getOpenFileNames', QPushButton('getOpenFileNames', clicked=self.__getOpenFileNames))
form.addRow('getSaveFileName', QPushButton('getSaveFileName', clicked=self.__getSaveFileName))
form.addRow('information', QPushButton('information', clicked=self.__information))
form.addRow('warningMessage', QPushButton('warningMessage', clicked=self.__warningMessage))
form.addRow('critical', QPushButton('critical', clicked=self.__critical))
def __getInt(self):
val, ok = QInputDialog.getInt(None, '整形', '请输入一个整数')
if ok:
print(val)
def __getDouble(self):
val, ok = QInputDialog.getDouble(None, '浮点', '请输入一个浮点数')
if ok:
print(val)
def __getText(self):
val, ok = QInputDialog.getText(None, '文字', '说说吧')
if ok:
print(val)
def __getItem(self):
val, ok = QInputDialog.getItem(None, '选择', '选个朋友', ('txq', 'qy', '小学妹'))
if ok:
print(val)
def __getColor(self):
# 和上面的放回值不一致
color = QColorDialog.getColor(Qt.black)
if color.isValid():
print(color.value())
def __getFont(self):
font, ok = QFontDialog.getFont(self.font())
if ok:
print(font)
def __getExistingDirectory(self):
dir = QFileDialog.getExistingDirectory(None)
if dir:
print(dir)
def __getOpenFileName(self):
filepath, _ = QFileDialog.getOpenFileName(None, '打开文件', os.getcwd(), '所有文件(*.*);;图片(*.jpg *.png)')
if filepath:
print(filepath)
def __getOpenFileNames(self):
filepath, _ = QFileDialog.getOpenFileNames(None, '打开文件', os.getcwd(), '所有文件(*.*);;图片(*.jpg *.png)')
if filepath:
print(filepath)
def __getSaveFileName(self):
filepath, _ = QFileDialog.getSaveFileName(None, '保存文件', os.getcwd(), '所有文件(*.*);;图片(*.jpg *.png)')
if filepath:
print(filepath)
def __information(self):
ret = QMessageBox.information(None, '警告', '你还没有激活软件,请抓紧充值', QMessageBox.Ok | QMessageBox.No)
if ret == QMessageBox.Ok:
print("ok")
else:
print("no")
def __warningMessage(self):
ret = QMessageBox.warning(None, '警告', '你还没有激活软件,请抓紧充值', QMessageBox.Ok | QMessageBox.No)
if ret == QMessageBox.Ok:
print("ok")
else:
print("no")
def __critical(self):
ret = QMessageBox.critical(None, '警告', '你还没有激活软件,请抓紧充值', QMessageBox.Ok | QMessageBox.No)
if ret == QMessageBox.Ok:
print("ok")
else:
print("no")
if __name__ == '__main__':
app = QApplication([])
w = Demo()
w.show()
app.exec_()
向导(QWizard)
QWidet
可以添加多个QWizardPage
,适合连续多页面的配置使用。
利用filed
机制,可以实现页面间的信息共享。
重写initPage
可以根据前边页面的设置,来初始化信息。
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGroupBox, QPushButton, QVBoxLayout, QWizard, QWizardPage, \
QFormLayout, QLineEdit
from PyQt5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtCore import Qt
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
vbox = QVBoxLayout(self)
btn = QPushButton("打开设置")
vbox.addWidget(btn)
btn.clicked.connect(self.do_clicked)
def do_clicked(self):
demo = SchoolWizard()
demo.exec()
info = demo.getAllInfo()
if info:
print(info)
class SchoolWizard(QWizard):
def __init__(self):
super(SchoolWizard, self).__init__()
self.addPage(HelloPage())
self.addPage(InfoPage())
self.addPage(ByePage())
self.acceptFlags = False
def accept(self) -> None:
self.acceptFlags = True
super(SchoolWizard, self).accept()
def getAllInfo(self):
if self.acceptFlags:
return {'name': self.field('name'), 'school': self.field('school')}
else:
return None
class HelloPage(QWizardPage):
def __init__(self):
super(HelloPage, self).__init__()
self.setTitle("欢迎")
self.setSubTitle("欢迎使用我们的演示软件")
vbox = QVBoxLayout(self)
vbox.addWidget(QLabel("你可以完全相信我们的服务,一定包君满意..."))
class InfoPage(QWizardPage):
def __init__(self):
super(InfoPage, self).__init__()
self.setTitle("填写信息")
form = QFormLayout(self)
editName = QLineEdit()
editSchool = QLineEdit()
form.addRow("姓名", editName)
form.addRow("学校", editSchool)
# 注册
self.registerField('name', editName)
self.registerField('school', editSchool)
class ByePage(QWizardPage):
def __init__(self):
super(ByePage, self).__init__()
self.setTitle("再见")
vbox = QVBoxLayout(self)
self.labBye = QLabel(f"")
vbox.addWidget(self.labBye)
def initializePage(self) -> None:
school = self.field('school')
self.labBye.setText(f'再见了,来自<b>{school}</b>的朋友....')
if __name__ == '__main__':
app = QApplication([])
w = MainWindow()
w.show()
app.exec_()
容器
QGroupBox
:用于将组件分组,QRadioBox就可以用这个来分组
ToolBox
:常用于拖动编程的地方,存放图像组件
QTabWidget
:常用于多个编辑区的切换
QStackedWidget
:常用于功能界面的切换
QDockWidget
:适合存放目录
QFrame
:用于分块
QWidget
:分块
QScrollArea
:滚动区域
QAxWidget
:不了解
一般而言,容器要配和布局使用;容器用于构建组件树,而布局则复制界面的布局绘制;
# stackedPage.py
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout, QPushButton, QVBoxLayout, QFormLayout, QFrame, \
QToolBox, QGroupBox, QListWidget, QStackedWidget
from PyQt5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtCore import Qt
"""
感觉和想象的差挺多的,他这个各个分组长度一致用起来很难受
"""
class Page(QWidget):
def __init__(self, parent=None, text="None"):
super().__init__(parent)
self.text = text
self.__buildUi()
def __buildUi(self):
vbox = QVBoxLayout(self)
vbox.addWidget(QLabel(self.text))
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.__buildUI()
def __buildUI(self):
grid = QGridLayout(self)
self.pages = QStackedWidget()
grid.addWidget(self.pages, 0, 1)
self.pages.addWidget(Page(text='Page1'))
self.pages.addWidget(Page(text='Page2'))
btnNext = QPushButton("next")
grid.addWidget(btnNext, 0, 0)
btnNext.clicked.connect(self.do_clicked)
def do_clicked(self):
index = self.pages.currentIndex()
index = (index + 1) % self.pages.count()
self.pages.setCurrentIndex(index)
if __name__ == '__main__':
app = QApplication([])
w = Demo()
w.show()
app.exec_()
# toolBox.py
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout, QPushButton, QVBoxLayout, QFormLayout, QFrame, \
QToolBox, QGroupBox, QListWidget
from PyQt5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtCore import Qt
"""
感觉和想象的差挺多的,他这个各个分组长度一致用起来很难受
"""
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.__buildUI()
def __buildUI(self):
grid = QGridLayout(self)
toolBox = QToolBox(self)
toolBox.layout().setSpacing(0)
# 动物
tboxAnimal = QFrame()
vbox = QVBoxLayout(tboxAnimal)
vbox.setSpacing(0)
vbox.setContentsMargins(5, 0, 0, 0)
btnDog = QPushButton('狗')
btnCat = QPushButton('猫')
btnRabbit = QPushButton('兔子')
vbox.addWidget(btnCat)
vbox.addWidget(btnDog)
vbox.addWidget(btnRabbit)
# 植物
tboxPlant = QFrame()
vbox = QVBoxLayout(tboxPlant)
vbox.setSpacing(0)
vbox.setContentsMargins(0, 0, 0, 0)
btnFlower = QPushButton('花')
btnTree = QPushButton('树')
vbox.addWidget(btnFlower)
vbox.addWidget(btnTree)
# 其他
tboxOther = QFrame()
toolBox.addItem(tboxAnimal, '动物')
toolBox.addItem(tboxPlant, '植物')
toolBox.addItem(tboxOther, '其他')
grid.addWidget(toolBox)
if __name__ == '__main__':
app = QApplication([])
w = Demo()
w.show()
app.exec_()
图标
QIcon
可以通过setIcon
设置到很多组件上;
一个QIcon有多个状态,每个状态可设置不同的图片:可以用来做目录的箭头;
tips: action可以设置act.setIconVisibleInMenu()
来单独设置图标在菜单中的可见性;
# simpleIcon.py
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QAction
from PyQt5.QtGui import QImage, QIcon, QPixmap
class Demo(QWidget):
def __init__(self):
super(Demo, self).__init__()
self.__buildUI()
# ================== 功能函数 ==================
def __buildUI(self):
vbox = QVBoxLayout(self)
btn = QPushButton("按钮")
btn.setIconSize(QSize(128, 128))
btn.setCheckable(True)
vbox.addWidget(btn)
icon = QIcon('0.png')
icon.addPixmap(QPixmap('1.png'), state=QIcon.On)
# icon.addPixmap(QPixmap('1.png'), mode=QIcon.Active, state=QIcon.Off)
# icon.addPixmap(QPixmap('1.png'), mode=QIcon.Selected, state=QIcon.On)
# icon.addPixmap(QPixmap('1.png'), mode=QIcon.Selected, state=QIcon.Off)
# icon.addPixmap(QPixmap('1.png'), mode=QIcon.Disabled, state=QIcon.Off)
# icon.addPixmap(QPixmap('1.png'), mode=QIcon.Selected, state=QIcon.Off)
btn.setIcon(icon)
if __name__ == '__main__':
app = QApplication([])
w = Demo()
w.show()
app.exec_()