QComboBox
内容的设置和更新
from PyQt5.QtWidgets import *
import sys
app = QApplication(sys.argv)
mainwindow = QMainWindow()
mainwindow.resize(200, 200)
# 设置下拉框
comboBox = QComboBox(mainwindow)
comboBox.addItems(['上', '中', '下'])
button = QPushButton('更新', mainwindow)
button.move(100, 100)
def updata_comboBox():
comboBox.clear() # 清空内容
comboBox.addItems(['A', 'B', 'C']) # 添加更新内容
button.clicked.connect(updata_comboBox)
mainwindow.show()
sys.exit(app.exec_())
运行结果:
默认值的设置
根据值设置:QComboBox(parent).setCurrentText(text)
根据下标设置:QComboBox(parent).setCurrentIndex(index)
在以上示例代码中添加以下代码:
comboBox.setCurrentText('下') # 根据值设置默认值
# 等同于:comboBox.setCurrentIndex(2) # 根据下标设置默认值
运行结果:
值和下标的获取
获取值:QComboBox(parent).currentText()
获取下标:QComboBox(parent).currentIndex()
from PyQt5.QtWidgets import *
import sys
app = QApplication(sys.argv)
mainwindow = QMainWindow()
mainwindow.resize(200, 200)
comboBox = QComboBox(mainwindow)
comboBox.addItems(['上', '中', '下'])
button1 = QPushButton('获取值', mainwindow)
button1.move(50, 50)
button1.clicked.connect(lambda : print(comboBox.currentText()))
button2 = QPushButton('获取下标', mainwindow)
button2.move(50, 100)
button2.clicked.connect(lambda : print(comboBox.currentIndex()))
mainwindow.show()
sys.exit(app.exec_())
运行结果: