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
在下拉选项索引发生改变时发射
例程
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)
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()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
运行效果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)