例子
让我们看看 QComboBox 小部件的一些功能是如何在以下示例中实现的。
项目通过 addItem() 方法单独添加到集合中,或者 List 对象中的项目通过addItems()方法。
self.cb.addItem("C++")
self.cb.addItems(["Java", "C#", "Python"])
QComboBox 对象发出 currentIndexChanged() 信号。它连接到selectionchange()方法。
组合框中的项目使用 itemText() 方法列出每个项目。属于当前所选项目的标签由currentText()方法。
def selectionchange(self,i):
print "Items in the list are :"
for count in range(self.cb.count()):
print self.cb.itemText(count)
print "Current index",i,"selection changed ",self.cb.currentText()
整个代码如下 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class combodemo(QWidget):
def __init__(self, parent = None):
super(combodemo, self).__init__(parent)
layout = QHBoxLayout()
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)
self.setLayout(layout)
self.setWindowTitle("combo box demo")
def selectionchange(self,i):
print "Items in the list are :"
for count in range(self.cb.count()):
print self.cb.itemText(count)
print "Current index",i,"selection changed ",self.cb.currentText()
def main():
app = QApplication(sys.argv)
ex = combodemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()