QComboBox
常用方法
addItem() | 添加一个下拉选项 |
addItems() | 从列表中添加下拉选项 |
Clear() | 删除下拉选项集合中的所有选项 |
count() | 返回下拉选项集合中的数目 |
currentText() | 返回选中选项的文本 |
itemText(i) | 获取索引为i的item的选项文本 |
currentIndex() | 返回选中项的索引 |
setltemText(int index,text) | 改变序号为index项的文本 |
常用信号
Activated | 当用户选中一个下拉选项时发射该信号 |
currentIndexChanged | 当下拉选项的索引发生改变时发射该信号 |
highlighted | 当选中一个已经选中的下拉选项时,发射该信号 |
代码示例
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("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)
comboxDemo = ComboxDemo()
comboxDemo.show()
sys.exit(app.exec_())