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

本文介绍了如何在PyQt5中使用QComboBox组件,包括设置默认值、动态更新选项、以及获取当前选中的值和下标。通过示例展示了如何操作和控制该控件的基本功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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_())

运行结果:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

街 三 仔

你的鼓励是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值