1 组合框(QComboBox)

组合框 — QComboBox
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout, QHBoxLayout from PyQt6.QtWidgets import QLabel, QPushButton, QComboBox from PyQt6.QtGui import QIcon, QAction from PyQt6.QtCore import Qt, QSize class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): # 创建组合框 self.cbb = QComboBox() # 数据删加 # 添加选项 items = ['选项一','选项二','选项三','选项四','选项五'] self.cbb.addItems(items) # 添加选项 items2 = [ ['voice.png','选项六'], ['voice.png','选项七'], ['voice.png','选项八'], ['voice.png','选项九'], ['voice.png','选项十'], ] for item in items2: self.cbb.addItem(QIcon(item[0]),item[1]) # 设置是否可以编辑组合件(缺省值为 False) self.cbb.setEditable(True) # 可通过 self.cbb.isEditable() 判断其是否可以编辑 # 用户输入新字符串时的操作 self.cbb.setInsertPolicy(QComboBox.InsertPolicy.InsertAtBottom) # InsertPolicy.NoInsert 不插入组合框中 # InsertPolicy.InsertAtTop 插入开头 # InsertPolicy.InsertAtCurrent 替换当前选项 # InsertPolicy.InsertAtBottom 插入末尾 # InsertPolicy.InsertAfterCurrent 插入当前项后 # InsertPolicy.InsertBeforeCurrent 插入当前项前 # InsertPolicy.InsertAlphabetically 按字符顺序插入组合框中 # 设置是否可以在组合件中输入重复项(缺省值为 True) self.cbb.setDuplicatesEnabled(True) # 可通过 self.cbb.duplicatesEnabled() 判断其是否可以输入重复项 # 外观设置 # 设置是否使用框架(缺省值为 True) self.cbb.setFrame(True) # 不用太丑了 # 可通过 self.cbb.hasFrame() 判断其是否可以使用框架 # 设置图标大小(缺省值为 QSize(16,16)) self.cbb.setIconSize(QSize(15,15)) # 可通过 self.cbb.iconSize() 返回图标大小 # 设置屏幕上允许的最大项目数(缺省值为 10) self.cbb.setMaxVisibleItems(25) # 可通过 self.cbb.maxVisibleItems() 返回屏幕上允许的最大项目数 # 设置屏幕上允许的最小项目数(缺省值为 0) self.cbb.setMinimumContentsLength(5) # 可通过 self.cbb.minimumContentsLength() 返回允许的最小数目 # 选项与索引 # 根据索引设置当前选项 self.cbb.setCurrentIndex(1) # 可通过 self.currentIndex() 返回当前索引 # 可通过 self.currentIndexChanged(int index) 传递索引变化信号 # 根据文本设置当前选项(必须可编辑) self.cbb.setCurrentText('选项三') # 可通过 self.currentText() 返回当前文本 # 可通过 self.currentTextChanged(text) 传递文本变化信号 # 返回选项数量 print(self.cbb.count()) # 返回当前选项 print(self.cbb.currentData()) # 事件 # 切换索引事件(int index)第一次选择时也激活 self.cbb.currentIndexChanged.connect(self.cbbindexchanged) # 文本变化事件(text) self.cbb.currentTextChanged.connect(self.cbbtextchanged) # 组合框激活事件(int index)第一次选择时也激活 self.cbb.activated.connect(self.cbbactived) # 组合框高光事件(int index) self.cbb.highlighted.connect(self.cbblightchanged) self.btn1 = QPushButton('删除当前信息') self.btn1.clicked.connect(self.clearcurrentone) self.btn2 = QPushButton('删除末尾选项') self.btn2.clicked.connect(self.clearlastone) self.btn3 = QPushButton('删除所有选项') self.btn3.clicked.connect(self.clearall) hbox = QHBoxLayout() hbox.addWidget(self.btn1) hbox.addWidget(self.btn2) hbox.addWidget(self.btn3) vbox = QVBoxLayout() vbox.addWidget(self.cbb) vbox.addLayout(hbox) widget = QWidget() widget.setLayout(vbox) self.setCentralWidget(widget) self.show() # 删除选项 def clearcurrentone(self): # 清除当前输入信息 self.cbb.clearEditText() def clearlastone(self): # 删除索引处选项 self.cbb.removeItem(self.cbb.count()-1) def clearall(self): # 删除全部选项 self.cbb.clear() # 事件 def cbbindexchanged(self,int): print('已选择第' + str(int+1) + '个选项') def cbbtextchanged(self,text): print('已选择:' + text) def cbbactived(self,int): print('已激活第' + str(int+1) + '个选项') def cbblightchanged(self,int): print('光标移动到第' + str(int+1) + '个选项') def cbbtextchanged(self,text): print('已输入:' + text) def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()
DLC
[QComboBox Class Qt Widgets 6.3.2](https://doc.qt.io/qt-6/qcombobox.html)

2 复选框(QCheckBox)


2.1 基本功能

选框 — QCheckBox
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QCheckBox from PyQt6.QtCore import Qt class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): # 复选框 # 创建 + 说明 qcb = QCheckBox('Show title', self) # 移动 qcb.move(20, 20) # 默认为被勾选状态 qcb.toggle() # 切换信号 qcb.stateChanged.connect(self.changeTitle) self.show() # 复选框切换事件 def changeTitle(self, state): # 这里之所以有一个 state 参数,是因为 22行 传递了复选框状态枚举 # 返回一下当时的信号值 print(state) # 返回一下当时的信号值对应的枚举 print(Qt.CheckState(state)) # 判断信号值与是否为全部选中 if state == Qt.CheckState.Checked.value: # Qt.CheckState.Checked 全部选中 value:2 # Qt.CheckState.PartiallyChecked 部分选中 value:1 # Qt.CheckState.Unchecked 全未选中 value:0 self.setWindowTitle('QCheckBox') else: self.setWindowTitle(' ') def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()
DLC
[List of All Members for QRadioButton Qt Widgets 5.15.10](https://doc.qt.io/qt-5/qradiobutton-members.html)

2.2 复选框三态(setCheckState)

选框 — QCheckBox
python from PyQt6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QCheckBox, QApplication, QPushButton,QMessageBox from PyQt6.QtCore import Qt import sys class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.cb = QCheckBox('全选',self) self.cb_a = QCheckBox('A',self) self.cb_b = QCheckBox('B',self) self.cb_c = QCheckBox('C',self) bt = QPushButton('提交',self) self.cb.stateChanged.connect(self.changecb1) self.cb_a.stateChanged.connect(self.changecb2) self.cb_b.stateChanged.connect(self.changecb2) self.cb_c.stateChanged.connect(self.changecb2) bt.clicked.connect(self.result) vbox1 = QVBoxLayout() vbox1.addWidget(self.cb_a) vbox1.addWidget(self.cb_b) vbox1.addWidget(self.cb_c) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addLayout(vbox1) hbox.addStretch(8) vbox = QVBoxLayout() vbox.addWidget(self.cb) vbox.addLayout(hbox) vbox.addWidget(bt) widget = QWidget() widget.setLayout(vbox) self.setCentralWidget(widget) print(self.size()) self.resize(200,50) self.show() def result(self): lis = [] if self.cb_a.isChecked(): lis.append('A') if self.cb_b.isChecked(): lis.append('B') if self.cb_c.isChecked(): lis.append('C') if lis == []: rst = '你没有选择答案啊!' else: rst = '你的答案是:' + ('、').join(lis) QMessageBox.information(self, '结果', rst) def changecb1(self): # 判断复选框是否为勾选状态 if self.cb.checkState() == Qt.CheckState.Checked: # 更改复选框勾选状态 self.cb_a.setChecked(True) self.cb_b.setChecked(True) self.cb_c.setChecked(True) elif self.cb.checkState() == Qt.CheckState.Unchecked: self.cb_a.setChecked(False) self.cb_b.setChecked(False) self.cb_c.setChecked(False) def changecb2(self): if self.cb_a.isChecked() and self.cb_b.isChecked() and self.cb_c.isChecked(): # 复选框三态设置:完全勾选;等同于二态中的勾选 self.cb.setCheckState(Qt.CheckState.Checked) elif self.cb_a.isChecked() or self.cb_b.isChecked() or self.cb_c.isChecked(): # 将复选框设置为三态复选框 self.cb.setTristate() # 复选框三态设置:部分勾选 self.cb.setCheckState(Qt.CheckState.PartiallyChecked) else: # 将复选框设置为二态复选框 self.cb.setTristate(False) # 复选框三态设置:完全未勾选;等同于二态中的未勾选 self.cb.setCheckState(Qt.CheckState.Unchecked) if __name__ == '__main__': app = QApplication(sys.argv) ex = QWindow() sys.exit(app.exec())

3 单选框(QRadioButton)

  • 功能为选框单选,其本质为按钮;
单选按钮 — QRadioButton
python from PyQt6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QRadioButton, QLabel, QApplication, QPushButton, QMessageBox, QButtonGroup import sys class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lb1 = QLabel('行为') self.lb2 = QLabel('对象') # 创建单选按钮 self.rb11 = QRadioButton('问候',self) self.rb12 = QRadioButton('感谢',self) self.rb13 = QRadioButton('告别',self) self.rb21 = QRadioButton('Peter',self) self.rb22 = QRadioButton('Joey',self) self.rb23 = QRadioButton('Lulu',self) # 单选按钮点击信号传递 self.rb11.clicked.connect(self.rbclicked) self.rb12.clicked.connect(self.rbclicked) self.rb13.clicked.connect(self.rbclicked) self.rb21.clicked.connect(self.rbclicked) self.rb22.clicked.connect(self.rbclicked) self.rb23.clicked.connect(self.rbclicked) self.btn = QPushButton('执行',self) self.btn.clicked.connect(self.btnclicked) self.info = '' vbox1 = QVBoxLayout() vbox1.addWidget(self.lb1) vbox1.addWidget(self.rb11) vbox1.addWidget(self.rb12) vbox1.addWidget(self.rb13) vbox2 = QVBoxLayout() vbox2.addWidget(self.lb2) vbox2.addWidget(self.rb21) vbox2.addWidget(self.rb22) vbox2.addWidget(self.rb23) hbox = QHBoxLayout() hbox.addLayout(vbox1) hbox.addLayout(vbox2) vbox3 = QVBoxLayout() vbox3.addLayout(hbox) vbox3.addWidget(self.btn) widget = QWidget() widget.setLayout(vbox3) self.setCentralWidget(widget) self.show() def rbclicked(self): sender = self.sender() # 判断是否选定 if sender.isChecked(): # 返回按钮上信息 self.info = sender.text() def btnclicked(self): QMessageBox.about(self,'你的选项是',self.info) def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()

4 普通按钮(QPushButton)


4.1 基本功能

普通按钮 — QPushButton
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton, QToolTip from PyQt6.QtGui import QFont, QIcon, QPixmap class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): QToolTip.setFont(QFont('SansSerif', 10)) # 创建按钮及快捷键 btn = QPushButton('&Quit', self) # '&Q...' Alt+Q 即可使用,QPushButton('Quit', self)不带快捷键 # self:父级部件,即放置按钮的部件,缺省时为顶级窗口 # 按钮位置 btn.move(50, 15) # 设置为默认按钮 btn.setDefault(True) # 默认按钮一个窗口只能有一个 # 按钮图标 btn.setIcon(QIcon(QPixmap('heihei.png'))) # 按钮大小设为系统默认值 btn.resize(btn.sizeHint()) # 按钮点击信号连接 btn.clicked.connect(QApplication.instance().quit) # QApplication.instance 返回 QCoreApplication对象(主事件循环); # ACoreApplication.quit 为退出应用程序; # 事件.connect 将退出应用程序信号由按钮组件传递给部件窗口。 # 按钮添加气泡提示器 btn.setToolTip('This is a <b>QPushButton</b> widget') self.resize(180,60) self.show() def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()
按钮信号
python btn.pressed.connect(self.connecter) # 按下触发 btn.release.connect(self.connecter) # 松开触发 btn.clicked.connect(self.connecter) # 下陷触发(切换按钮) btn.toggled.connect(self.connecter) # 状态变化触发

4.2 不可用按钮(setEnable)

普通按钮 — QPushButton
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton, QMessageBox from PyQt6.QtCore import QTimer class QWindow(QMainWindow): def __init__(self): super().__init__() self.resize(180,150) self.initUI() def initUI(self): self.btn = QPushButton('发送验证码',self) self.btn.clicked.connect(self.btnclicked) # 创建计时器 self.time = QTimer(self) # 设置计时器时间间隔(单位:ms;1s = 1000ms) self.time.setInterval(1000) # 计时器每经过一个时间间隔,便发出一次信号 self.time.timeout.connect(self.Refresh) self.count = 10 self.resize(180,60) self.setCentralWidget(self.btn) self.show() def btnclicked(self): if self.btn.isEnabled(): # 使用计时器 self.time.start() # 按钮不可用 self.btn.setEnabled(False) def Refresh(self): if self.count > 0: self.btn.setText(str(self.count)+'秒后重发') self.count -= 1 else: self.time.stop() # 按钮可用 self.btn.setEnabled(True) self.btn.setText('发送验证码') self.count = 10 def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()

4.3 切换按钮(setCheckable)

普通按钮 — QPushButton
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton class QWindow(QMainWindow): def __init__(self): super().__init__() self.resize(180,150) self.initUI() def initUI(self): self.btn = QPushButton('有本事按我啊', self) # 设置按钮为切换按钮 self.btn.setCheckable(True) # 按钮点击事件连接 self.btn.clicked[bool].connect(self.btnclicked) # clicked[bool] 切换按钮传递布朗值信号 # 开启排他性 self.btn.setAutoExclusive(True) self.resize(180,60) self.setCentralWidget(self.btn) self.show() def btnclicked(self, state): # 返回按钮信息(bool) if self.btn.isChecked(): self.btn.setText('被按下去了(变蓝了)') else: self.btn.setText('有本事按我啊') def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()

4.4 选项按钮(SetMenu)

按钮中的选项是通过菜单+行为实现的

普通按钮 — QPushButton
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton, QToolTip, QMenu, QMessageBox from PyQt6.QtGui import QFont class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): QToolTip.setFont(QFont('SimSuncss', 10)) # 创建子菜单 menu = QMenu(self) # 添加事件 act1 = menu.addAction('Peter') # 事件触发信号连接 act1.triggered.connect(self.acttriggered) # 子菜单中添加分割线 menu.addSeparator() act2 = menu.addAction('Joey') act2.triggered.connect(self.acttriggered) act3 = menu.addAction('Lulu') act3.triggered.connect(self.acttriggered) menu.addSeparator() btn = QPushButton('你谁啊?', self) btn.setDefault(True) btn.setToolTip('选择你的名字') # 按钮设置成子菜单 btn.setMenu(menu) self.resize(180,60) self.setCentralWidget(btn) self.show() def acttriggered(self): sender = self.sender() # 返回行为名 QMessageBox.about(self,'结果','啊,卧槽,你就是' + sender.text()+ '啊!牛逼牛逼!!!') def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()

5 按钮组(QButtonGroup)

  • 通常应用于“单选框”和“切换按钮”;
单选按钮 — QRadioButton
python from PyQt6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QRadioButton, QLabel, QApplication, QPushButton, QMessageBox, QButtonGroup import sys class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lb1 = QLabel('行为') self.lb2 = QLabel('对象') self.rb11 = QRadioButton('问候',self) self.rb12 = QRadioButton('感谢',self) self.rb13 = QRadioButton('告别',self) self.rb21 = QRadioButton('Peter',self) self.rb22 = QRadioButton('Joey',self) self.rb23 = QRadioButton('Lulu',self) # 创建按钮组 self.bg1 = QButtonGroup(self) # 按钮组添加成员 self.bg1.addButton(self.rb11, 11) # ButtonGroup.addButton(按钮, 定义编号) self.bg1.addButton(self.rb12, 12) self.bg1.addButton(self.rb13, 13) # 编号缺省时,缺省值为负数,故最好写成正数防错 # 按钮组按钮点击信号连接 self.bg1.buttonClicked.connect(self.rbclicked) self.bg2 = QButtonGroup(self) self.bg2.addButton(self.rb21, 21) self.bg2.addButton(self.rb22, 22) self.bg2.addButton(self.rb23, 23) self.bg2.buttonClicked.connect(self.rbclicked) self.btn = QPushButton('执行',self) self.btn.clicked.connect(self.btnclicked) self.info1 = '' self.info2 = '' vbox1 = QVBoxLayout() vbox1.addWidget(self.lb1) vbox1.addWidget(self.rb11) vbox1.addWidget(self.rb12) vbox1.addWidget(self.rb13) vbox2 = QVBoxLayout() vbox2.addWidget(self.lb2) vbox2.addWidget(self.rb21) vbox2.addWidget(self.rb22) vbox2.addWidget(self.rb23) hbox = QHBoxLayout() hbox.addLayout(vbox1) hbox.addLayout(vbox2) vbox3 = QVBoxLayout() vbox3.addLayout(hbox) vbox3.addWidget(self.btn) widget = QWidget() widget.setLayout(vbox3) self.setCentralWidget(widget) self.show() def rbclicked(self): sender = self.sender() if sender == self.bg1: # 判断按钮组所选按钮的编号 if self.bg1.checkedId() == 11: self.info1 = '你好!' elif self.bg1.checkedId() == 12: self.info1 = '感谢!' elif self.bg1.checkedId() == 13: self.info1 = '再见!' else: self.info1 = '' else: if self.bg2.checkedId() == 21: self.info2 = 'Peter~' elif self.bg2.checkedId() == 22: self.info2 = 'Joey~' elif self.bg2.checkedId() == 23: self.info2 = 'Lulu~' else: self.info2 = '' def btnclicked(self): QMessageBox.about(self,'你的选项是',self.info1 + self.info2) def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()

6 工具按钮(QToolButton)


6.1 选项卡式

工具按钮 — QToolButton
python import sys from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton, QMessageBox, QToolTip, QToolButton from PyQt6.QtCore import QTimer, Qt, QUrl from PyQt6.QtWidgets import QMenu from PyQt6.QtGui import QIcon, QAction, QFont, QDesktopServices class QWindow(QMainWindow): def __init__(self): super().__init__() self.resize(180,150) self.initUI() def initUI(self): QToolTip.setFont(QFont('SimSuncss', 10)) self.act_peter = QAction(QIcon('icon/Peter.ico'),'Peter', self) self.act_peter.triggered.connect(self.on_click) self.act_joey = QAction(QIcon('icon/Joey.ico'),'Joey', self) self.act_joey.triggered.connect(self.on_click) self.act_lulu = QAction(QIcon('icon/Lulu.ico'),'Lulu', self) self.act_lulu.triggered.connect(self.on_click) menu = QMenu(self) menu.addAction(self.act_peter) menu.addSeparator() menu.addAction(self.act_joey) menu.addAction(self.act_lulu) # 创建工具按钮 tb = QToolButton(self) # 设置工具按钮显示内容 tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) # Qt.ToolButtonStyle.ToolButtonIconOnly 只显示图标 # Qt.ToolButtonStyle.ToolBUttonTextOnly 只显示文字 # Qt.ToolButtonStyle.ToolTextBesideIco 文字在图表旁 # Qt.ToolButtonStyle.ToolButtonTextUnderIconn 文字在图标下 # Qt.ToolButtonStyle.ToolButtonFollowStyle 系统默认设置(只显示图标) # 设置工具按钮下拉栏方向(文字左侧小按钮,感觉没用不设置) tb.setArrowType(Qt.ArrowType.NoArrow) # Qt.ArrowType.NoArrow 无箭头(缺省值) # Qt.ArrowType.UpArrow 向上箭头 # Qt.ArrowType.DownArrow 向下箭头 # Qt.ArrowType.LeftArrow 向左箭头 # Qt.ArrowType.RightArrow 向右箭头 # 设置气泡窗口 tb.setToolTip('选择爸爸或者女儿') # 箭头大小和响应时间 tb.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup) # QToolButton.ToolButtonPopupMode.DelayedPopup 小箭头,长按弹出子菜单 # QToolButton.ToolButtonPopupMode.MenuButtonPopup 大箭头,点击弹出子菜单 # QToolButton.ToolButtonPopupMode.InstantPopup 小箭头,点击弹出子菜单 # 设置文字 tb.setText('选择角色') # 设置图标 tb.setIcon(QIcon('icon/bank.ico')) # 是否自动升起 tb.setAutoRaise(True) # 设置子菜单 tb.setMenu(menu) self.show() def on_click(self): if self.sender() == self.act_peter: # 打开网页 QDesktopServices.openUrl(QUrl('https://baike.baidu.com/item/peter/16280#viewPageContent')) elif self.sender() == self.act_joey: QDesktopServices.openUrl(QUrl('https://baike.baidu.com/item/joey/52931445')) else: QDesktopServices.openUrl(QUrl('https://baike.baidu.com/item/LULU/6163605#viewPageContent')) def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()
DLC
[QToolButton Class Qt Widgets 6.3.2](https://doc.qt.io/qt-6/qtoolbutton.html)

6.2 图标式

工具按钮 — QToolButton
python import sys, webbrowser from PyQt6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QApplication, QToolButton from PyQt6.QtCore import Qt from PyQt6.QtGui import QIcon class QWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): # 创建工具箱 tb = QToolButton() # 设置工具箱描述 tb.setText('笔记') # 设置工具箱图标 tb.setIcon(QIcon('voice.png')) # 设置工具箱图标大小 tb.setIconSize(QSize(32,32)) # 设置工具箱鼠标移动过去,才凹陷 tb.setAutoRaise(True) # 设置工具箱文字和图标的位置关系 tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) # Qt.ToolButtonStyle.ToolButtonIconOnly 只显示图标 # Qt.ToolButtonStyle.ToolButtonTextOnly 只显示文本 # Qt.ToolButtonStyle.ToolButtonTextBesideIcon 文本出现在图标旁边 # Qt.ToolButtonStyle.ToolButtonTextUnderIcon 文本出现在图标下方 # Qt.ToolButtonStyle.ToolButtonFollowStyle # 工具箱点击信号 tb.clicked.connect(self.tbclicked) vbox = QVBoxLayout() vbox.addWidget(tb) widget = QWidget() widget.setLayout(vbox) self.setCentralWidget(widget) self.show() def tbclicked(self): webbrowser.open('https://www.yuque.com/u0_zui/python') def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()

7 工具箱(QToolBox)

**工具箱 — QToolBox 组合框 — QGroupBox**
python import sys, webbrowser from PyQt6.QtWidgets import QMainWindow, QApplication, QWidget, QToolBox, QGroupBox, QToolButton, QVBoxLayout from PyQt6.QtCore import Qt, QSize from PyQt6.QtGui import QPixmap, QIcon class QWindow(QMainWindow): def __init__(self): super().__init__() self.resize(180,150) self.initUI() def initUI(self): # 创建工具箱 tbox = QToolBox() # 设置工具箱的窗口系统属性 tbox.setWindowFlags(Qt.WindowType.Dialog) # Qt.WindowType.Dialog 为 QDialog的默认类型,将窗口装饰为对话框窗口 self.stuffs = { '主人公':{ 'Peter':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'}, 'Joey':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'}, 'Lulu':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'}, '小受':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'} }, '跑龙套':{ '小A':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'}, '小B':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'}, '小C':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'}, '小D':{'png':'voice.png','link':'https://www.yuque.com/u0_zui/python'} } } for group, stuff in self.stuffs.items(): # 创建组合框 gb = QGroupBox() # 创建组合框的垂直排列 vbox = QVBoxLayout(gb) vbox.setAlignment(Qt.AlignmentFlag.AlignCenter) for name, prop in stuff.items(): tb = QToolButton() tb.setText(name) tb.setIcon(QIcon(prop['png'])) tb.setIconSize(QSize(32,32)) tb.setAutoRaise(True) tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) tb.clicked.connect(self.tbclicked) # 工具按钮添加到工具箱中 vbox.addWidget(tb) # 将组合框添加到工具箱中 tbox.addItem(gb, group) self.setCentralWidget(tbox) self.resize(100,350) self.show() def tbclicked(self): sender = self.sender() if self.stuffs['主人公'].get(sender.text()) == None: webbrowser.open(self.stuffs['跑龙套'][sender.text()]['link']) else: webbrowser.open(self.stuffs['主人公'][sender.text()]['link']) def main(): app = QApplication(sys.argv) qw = QWindow() sys.exit(app.exec()) if __name__ == '__main__': main()