PyQt5之QComboBox下拉列表框

本文详细介绍了PyQt5中QComboBox控件的使用方法,包括常用方法如addItem(), addItems()等,以及如何处理Activated, currentIndexChanged等信号。通过实例展示了如何创建下拉列表框,添加选项,并在选项改变时更新界面。

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

PyQt5之QComboBox下拉列表框

QComboBox是一个集按钮和下拉选项于一体的控件,也被称为下拉列表框。

一、QComboBox类中的常用方法

方法描述
addItem()添加一个下拉选项
addItems()从列表中添加下拉选项
Clear()删除下拉选项集合中的所有选项
count()返回下拉选项集合中的数目
currentText()返回选中选项的文本
itemText(i)获取索引为 i 的 item 的选项文本
currentIndex()返回选中项的索引
setItemText(int index,text)改变序号为 index 项的文本

二、QComboBox类中的常用信号

信号含义
Activated当用户选中一个下拉选项时发射该信号
currentIndexChanged当下拉选项的索引发生改变时发射该信号
highlighted当选中一个已经选中的下拉选项时,发射该信号

三、QComboBox按钮的使用

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class Win(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 200, 400, 400)
        self.setWindowTitle('QComboBox的使用')

        self.lb1 = QLabel('')
        self.cb = QComboBox()
        self.cb.addItem('C')
        self.cb.addItem('C++')
        self.cb.addItems(['Java','Python','C#'])
        self.cb.currentIndexChanged.connect(self.selectionchange)

        layout = QVBoxLayout()
        layout.addWidget(self.cb)
        layout.addWidget(self.lb1)
        self.setLayout(layout)

    def selectionchange(self,i):
        self.lb1.setText(self.cb.currentText())
        print('Items in the list are:')
        for count in range(self.cb.count()):
            print('item'+str(count)+'='+self.cb.itemText(count))
            print('Current index',i,'selection changed',self.cb.currentText())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = Win()
    form.show()
    sys.exit(app.exec_())

运行效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值