当前位置:首页 > 编程笔记 > 正文
已解决

【PyQt小知识 - 3】: QComboBox下拉框内容的设置和更新、默认值的设置、值和下标的获取

来自网友在路上 191891提问 提问时间:2023-11-22 02:04:51阅读次数: 91

最佳答案 问答题库918位专家为你答疑解惑

QComboBox

内容的设置和更新

from PyQt5.QtWidgets import *
import sysapp = 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 sysapp = 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_())

运行结果:

在这里插入图片描述
在这里插入图片描述

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"【PyQt小知识 - 3】: QComboBox下拉框内容的设置和更新、默认值的设置、值和下标的获取":http://eshow365.cn/6-41723-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!