<>pyQT5中ComboBox的用法
<>常用的方法
1、添加下拉选项
#添加一个下拉选项 self.comboBox.addItem("默认文本") #从列表中添加下拉选项 self.comboBox.addItems([
"文本1", "文本2", "文本3"])
2、设置显示项目
self.comboBox.setCurrentIndex(2)
3、获取选项中的索引
self.comboBox.currentIndex()
4、获取选中项的文本
self.comboBox.currentText()
<>常用的信号
1、activated
在用户选中一个下拉选项时发射
2、currentIndexChanged
在下拉选项索引发生改变时发射
<>例程
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file
'ex_combox.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, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow") MainWindow.resize(744, 286) self.
centralwidget= QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName(
"centralwidget") self.comboBox = QtWidgets.QComboBox(self.centralwidget) self.
comboBox.setGeometry(QtCore.QRect(150, 20, 351, 51)) self.comboBox.setObjectName
("comboBox") self.label = QtWidgets.QLabel(self.centralwidget) self.label.
setGeometry(QtCore.QRect(150, 100, 341, 31)) self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.
QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 744, 23)) 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) self.comboBox.
addItems(["文本1","文本2","文本3","文本4","文本5"]) self.comboBox.setCurrentIndex(3) #
设置默认显示的值,不设置则默认为0 self.comboBox.currentIndexChanged.connect(self.show) # 关联信号与槽
def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.
translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self
.label.setText(_translate("MainWindow", "")) def show(self): self.label.setText(
"当前选择是第{}项,文本内容为:{}".format(self.comboBox.currentText(),self.comboBox.
currentText())) import sys if __name__ == '__main__': app = QtWidgets.
QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() # 创建窗体对象 ui =
Ui_MainWindow() # 创建PyQt设计的窗体对象 ui.setupUi(MainWindow) # 调用窗体的方法对对象进行初始化设置
MainWindow.show() # 显示窗体 sys.exit(app.exec_()) # 程序关闭时退出进程
运行效果: