PyQt5基本窗口控件(QComboBox(下拉列表框))

QComboBox(下拉列表框)

QComboBox是一个集按钮和下拉选项于一体的控件,也被称为下拉列表框。
QComboBox类中的常用方法如表4-6所示。

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

QComboBox类中的常用信号如表4-17所示。

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

QComboBox按钮的使用

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

class ComboxDemo(QWidget):
    def __init__(self,parent=None):
        super(ComboxDemo,self).__init__(parent)
        self.setWindowTitle("combox例子")
        self.resize(300,90)
        layout=QVBoxLayout()
        self.lbl=QLabel("")

        self.cb=QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        layout.addWidget(self.cb)
        layout.addWidget(self.lbl)
        self.setLayout(layout)

    def selectionchange(self,i):
        self.lbl.setText(self.cb.currentText())
        self.lbl.adjustSize()

        print("Itemsin the list are.")
        for count in range(self.cb.count()):
            print('item'+str(count)+'='+self.cb.ItemText(count))
            print("Currentindex",i,"selection changed",self.cb.currentText())

if __name__=='__main__':
    app=QApplication(sys.argv)
    comboDemo=ComboxDemo()
    comboDemo.show()
    sys.exit(app.exec_())

运行结果

PyQt5基本窗口控件(QComboBox(下拉列表框))_第1张图片

代码分析:
在这个例子中显示了一个下拉列表框和一个标签,其中下拉列表框中有5个选
项,既可以使用QComboBox的addltem()方法添加单个选项,也可以使用addltems()
方法添加多个选项:标签显示的是从下拉列表框中选择的选项,

 self.cb=QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])

当下拉列表框中的选项发生改变时将发射currentlndexChanged信号,连接到自
定义的槽函数selectionchange()。

self.cb.currentIndexChanged.connect(self.selectionchange)

在方法中,当选中下拉列表框中的一个选项时,将把该选项的文本设置为标签
的文本,并调整标签的大小。

 def selectionchange(self,i):
        self.lbl.setText(self.cb.currentText())

你可能感兴趣的:(PyQt5快速开发与实战,qt,python,开发语言)