Argus Argus - 1 year ago 100
Python Question

Inserting hidden data into a combobox pyqt

I'm not sure if this can be done or if there is a better way to do it. Nonetheless, I've got a database from which I can insert a lot of items into a combobox, however to search and delete for that specific data I need to be able to place each row's id within the combobox. However I'm not entirely sure about how to do this with PyQT.

If anyone could help me I'd appreciate it. It would certainly make my life easier if those id's were in there, but I can't show them because there's no way a normal user would ever understand them.

Answer Source

The standard API for adding items already does exactly what you want:

# add some items with associated data
for identifier in (123, 456, 789):
    combo.addItem('text', identifier)

More than one piece of data can be associated with each item by using a different role for each one (the default role is QtCore.Qt.UserRole):

combo.setItemData(index, 'other data', QtCore.Qt.UserRole + 1)

You can then find items by data/role:

index = combo.findData(456)
if index >= 0:
    print(combo.itemData(index, QtCore.Qt.UserRole + 1)) # prints "other data"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download