PyQt5入门(四)--------下拉选择框控件(comboBox)
目录
- QComboBox 用法表
- addItem(str)、addItems ([str1,str2,str3])
- insertItem(int,str)、insertItems(int,[str1,str2])
- setCurrentIndex(int)、setCurrentText(str)
- currentIndex() 、currentIndex()
- removeItem(int) 、clear()
- setMaxVisibleItems(int)
- setEditable
- setAlignment(Qt.AlignCenter)
- setStyleSheet
- activated(int) 、currentIndexChanged(int)信号
- currentTextChanged(str)
- highlighted(int)
QComboBox 是 PyQt5 中常用的下拉选择框控件,用于显示一个可选列表,用户可以从中选择一个选项,也可以在某些情况下允许用户输入自定义文本。
QComboBox 用法表
QComboBox 方法表如下:
方法 | 说明 |
---|---|
addItem(str) | 添加一个选项 |
addItems ([str1,str2,str3]) | 添加多个选项 |
insertItem(int,str) | 插入一个选项 |
insertItems(int,[str1,str2]) | 插入多个选项 |
setCurrentIndex(0) | 设置索引为0的项作为当前选中项 |
setCurrentText(str) | 设置文本匹配的项作为当前选中项 |
currentIndex() | 获取当前选项索引 |
currentText() | 获取当前选项文本 |
removeItem(1) | 删除索引为 1 的选项 |
clear() | 清空所有选项 |
setMaxVisibleItems(int) | 设置下拉框中最多显示选项数量 |
setAlignment(Qt.AlignCenter) | 设置下拉框对齐方式 |
setStyleSheet | 设置样式表 |
QComboBox 信号表如下:
信号 | 说明 |
---|---|
currentIndexChanged(int) | 当前选项索引改变时发出信号(手动选择或者程序选择),传递索引 |
currentTextChanged(str) | 当前选项文本改变时发出信号 ,传递文本 |
activated(int) | 用户手动选择某个选项时才会触发,传递索引 |
highlighted(int) | 鼠标悬停选项时触发,传递索引 |
addItem(str)、addItems ([str1,str2,str3])
添加单个选项:
self.combo_box.addItem("Option 1") # 添加一个选项
添加多个选项:
self.combo_box.addItems(["Option 1", "Option 2", "Option 3"]) # 添加多个选项
insertItem(int,str)、insertItems(int,[str1,str2])
基础语法:
self.combo_box.insertItem(1, "Inserted Option") # 在索引 1 插入选项
self.combo_box.insertItems(2, ["Option A", "Option B"]) # 从索引 2 开始插入多个选项
setCurrentIndex(int)、setCurrentText(str)
self.combo_box.setCurrentIndex(0) # 设置索引为0的项作为当前选中项
self.combo_box.setCurrentText("Option 2") # 设置文本匹配“Option 2”的项作为当前选中项
currentIndex() 、currentIndex()
语法:
current_index = self.combo_box.currentIndex() # 获取当前选项索引
current_text = self.combo_box.currentText() # 获取当前选项文本
print(f"当前索引: {current_index}, 当前文本: {current_text}")
removeItem(int) 、clear()
用法:
self.combo_box.removeItem(1) # 删除索引为 1 的选项
self.combo_box.clear() # 清空所有选项
setMaxVisibleItems(int)
self.combo_box.setMaxVisibleItems(5) # 设置下拉框中最多显示 5 个选项
setEditable
self.combo_box.setEditable(True) # 允许用户编辑/输入
self.combo_box.setEditable(False) # 只允许选择,不允许编辑
setAlignment(Qt.AlignCenter)
from PyQt5.QtCore import Qt
self.combo_box.setEditable(True)
self.combo_box.lineEdit().setAlignment(Qt.AlignCenter) # 设置输入框对齐方式
setStyleSheet
self.combo_box.setStyleSheet("""QComboBox {background-color: lightblue;border: 1px solid black;}QComboBox::drop-down {background-color: lightgray;}
""")
activated(int) 、currentIndexChanged(int)信号
# 选项索引变化信号到槽函数
self.comboBox1.currentIndexChanged.connect(self.on_index_changed)#手动或者程序改变选项都可以触发
self.comboBox1.activated.connect(self.on_index_changed)#只能手动选择选项触发
currentTextChanged(str)
# 选项文本变化信号到槽函数
self.comboBox1.currentTextChanged.connect(self.on_text_changed)
highlighted(int)
# 选项悬停信号到槽函数
self.comboBox1.highlighted.connect(self.on_highlighted) #鼠标悬停选项时触发,传递索引
以上用法综合演示。
testUI.py代码:
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'testUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(693, 620)sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)sizePolicy.setHorizontalStretch(4)sizePolicy.setVerticalStretch(12)sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())MainWindow.setSizePolicy(sizePolicy)MainWindow.setMaximumSize(QtCore.QSize(16777215, 16777215))MainWindow.setBaseSize(QtCore.QSize(0, 0))self.centralwidget = QtWidgets.QWidget(MainWindow)self.centralwidget.setObjectName("centralwidget")self.comboBox1 = QtWidgets.QComboBox(self.centralwidget)self.comboBox1.setGeometry(QtCore.QRect(90, 140, 241, 41))self.comboBox1.setObjectName("comboBox1")self.label2 = QtWidgets.QLabel(self.centralwidget)self.label2.setGeometry(QtCore.QRect(90, 70, 251, 21))self.label2.setObjectName("label2")self.Button1 = QtWidgets.QPushButton(self.centralwidget)self.Button1.setGeometry(QtCore.QRect(90, 210, 261, 41))self.Button1.setObjectName("Button1")self.Button2 = QtWidgets.QPushButton(self.centralwidget)self.Button2.setGeometry(QtCore.QRect(90, 270, 261, 41))self.Button2.setObjectName("Button2")self.Button5 = QtWidgets.QPushButton(self.centralwidget)self.Button5.setGeometry(QtCore.QRect(390, 450, 261, 41))self.Button5.setObjectName("Button5")self.Button3 = QtWidgets.QPushButton(self.centralwidget)self.Button3.setGeometry(QtCore.QRect(90, 330, 261, 41))self.Button3.setObjectName("Button3")self.Button4 = QtWidgets.QPushButton(self.centralwidget)self.Button4.setGeometry(QtCore.QRect(90, 390, 261, 41))self.Button4.setObjectName("Button4")self.Button6 = QtWidgets.QPushButton(self.centralwidget)self.Button6.setGeometry(QtCore.QRect(390, 210, 261, 41))self.Button6.setObjectName("Button6")self.Button7 = QtWidgets.QPushButton(self.centralwidget)self.Button7.setGeometry(QtCore.QRect(390, 270, 261, 41))self.Button7.setObjectName("Button7")self.Button8 = QtWidgets.QPushButton(self.centralwidget)self.Button8.setGeometry(QtCore.QRect(390, 330, 261, 41))self.Button8.setObjectName("Button8")self.Button9 = QtWidgets.QPushButton(self.centralwidget)self.Button9.setGeometry(QtCore.QRect(390, 390, 261, 41))self.Button9.setObjectName("Button9")self.label1 = QtWidgets.QLabel(self.centralwidget)self.label1.setGeometry(QtCore.QRect(90, 40, 251, 21))self.label1.setObjectName("label1")self.label3 = QtWidgets.QLabel(self.centralwidget)self.label3.setGeometry(QtCore.QRect(90, 100, 251, 21))self.label3.setObjectName("label3")MainWindow.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(MainWindow)self.menubar.setGeometry(QtCore.QRect(0, 0, 693, 22))self.menubar.setObjectName("menubar")MainWindow.setMenuBar(self.menubar)self.statusbar = QtWidgets.QStatusBar(MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)self.retranslateUi(MainWindow)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))self.label2.setText(_translate("MainWindow", "当前选项文本:"))self.Button1.setText(_translate("MainWindow", "添加一个选项"))self.Button2.setText(_translate("MainWindow", "添加两个选项"))self.Button5.setText(_translate("MainWindow", "最多显示3个选项"))self.Button3.setText(_translate("MainWindow", "顶部插入一个选项"))self.Button4.setText(_translate("MainWindow", "索引2后面插入两个选项"))self.Button6.setText(_translate("MainWindow", "显示索引为0得选项"))self.Button7.setText(_translate("MainWindow", "显示文本为“选项1”的选项"))self.Button8.setText(_translate("MainWindow", "删除索引为1的选项"))self.Button9.setText(_translate("MainWindow", "清空所有选项"))self.label1.setText(_translate("MainWindow", "当前选项索引:"))self.label3.setText(_translate("MainWindow", "悬停选项索引:"))
run_demo.py代码:
import sys
from PyQt5.QtGui import QFont, QIntValidator, QDoubleValidator, QColor, QTextCursor
import testUI
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from testUI import Ui_MainWindow
from PyQt5.QtCore import Qtclass Window(QMainWindow,Ui_MainWindow):def __init__(self,parent=None):super(Window, self).__init__(parent)self.setupUi(self)self.init_comboBox() # 初始化调用 init_comboBox函数self.init_button() # 初始化调用init_button()函数def init_button(self):self.Button1.clicked.connect(self.add_one_option)self.Button2.clicked.connect(self.add_two_options)self.Button3.clicked.connect(self.insert_one_option)self.Button4.clicked.connect(self.insert_two_option)self.Button5.clicked.connect(self.set_MaxVisibleItems)self.Button6.clicked.connect(self.set_currentoption_index)self.Button7.clicked.connect(self.set_currentoption_text)self.Button8.clicked.connect(self.delete_option)self.Button9.clicked.connect(self.clear_options)def init_comboBox(self):# 选项索引变化信号到槽函数self.comboBox1.currentIndexChanged.connect(self.on_index_changed)# 选项文本变化信号到槽函数self.comboBox1.currentTextChanged.connect(self.on_text_changed)# 选项悬停信号到槽函数self.comboBox1.highlighted.connect(self.on_highlighted)def on_index_changed(self, index):# 顶部标签显示当前选择项索引# currentIndex=self.comboBox1.currentIndex()self.label1.setText(f"当前选项索引: {index}")def on_text_changed(self, text):# 顶部标签显示当前选择项的文本# currentText=self.comboBox1.currentText()self.label2.setText(f"当前选项文本: {text}")def on_highlighted(self, index):# 当某个选项被悬停或高亮时触发self.label3.setText(f"悬停选项索引: {index}")def add_one_option(self):# 添加一个选项self.comboBox1.addItem('选项1')def add_two_options(self):# 添加两个选项self.comboBox1.addItems(['选项2','选项3'])def insert_one_option(self):# 顶部插入一个选项self.comboBox1.insertItem(0,'顶部插入的选项4')def insert_two_option(self):# 索引2后面插入两个选项self.comboBox1.insertItems(1,['选项5','选项6'])def set_currentoption_index(self):# 设设置索引为0的项作为当前选中项self.comboBox1.setCurrentIndex(0)def set_currentoption_text(self):# 设置文本匹配的项作为当前选中项self.comboBox1.setCurrentText('选项1')def delete_option(self):# 删除索引为1的选项self.comboBox1.removeItem(1)def clear_options(self):# 清空所有选项self.comboBox1.clear()def set_MaxVisibleItems(self):# 最多显示3个选项self.comboBox1.setMaxVisibleItems(3)
if __name__ == '__main__':# 实例化,传参app = QApplication(sys.argv)# 创建对象mainWindow = Window()# 创建窗口mainWindow.show()# 进入程序的主循环,并通过exit函数确保主循环安全结束(该释放资源的一定要释放)sys.exit(app.exec_())
演示效果图: