Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setData to QComboBox in PyQt/PySide?

Here's how I add data to a QListWidgetItem using setData. 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?

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

self.myListWidget.addItem( item )                       
like image 902
fredrik Avatar asked Dec 26 '22 13:12

fredrik


1 Answers

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:

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_()
like image 174
Alvaro Fuentes Avatar answered Jan 10 '23 01:01

Alvaro Fuentes