简体   繁体   English

如何在PyQt / PySide中将数据设置为QComboBox?

[英]How to setData to QComboBox in PyQt/PySide?

Here's how I add data to a QListWidgetItem using setData . 以下是使用setData将数据添加到QListWidgetItem的方法。 How can I add data in a similar way (hiding it) but to a QComboBox item - and how can I retrieve this data from the QComboBoxItems once it's in there? 如何以类似的方式添加数据(隐藏它),但是添加到QComboBox项目 - 如何在QComboBoxItems中检索此数据?

item = QtGui.QListWidgetItem()
item.setText( myText )
item.setData( QtCore.Qt.UserRole, myData)

self.myListWidget.addItem( item )                       

You can use QComboBox.addItem (self, QString text, QVariant userData = QVariant()) to add items and QComboBox.itemData (self, int index, int role = Qt.UserRole) to retrieve the data: 您可以使用QComboBox.addItem (self, QString text, QVariant userData = QVariant())添加项目和QComboBox.itemData (self, int index, int role = Qt.UserRole)来检索数据:

import PyQt4.QtGui as gui, PyQt4.QtCore as core

app = gui.QApplication([])

cb = gui.QComboBox()

cb.addItem('int 1',1)
cb.addItem('int 2',2)
cb.addItem('int 3',3)
cb.addItem('int 4',4)

print cb.itemData(0).toInt()[0]

core.pyqtSlot('int')
def f(index):
    data,can_convert =  cb.itemData(index).toInt()
    if can_convert:
        print 'integer:',data

cb.currentIndexChanged.connect(f)

cb.show()

app.exec_()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM