ZioByte
ZioByte

Reputation: 2994

PyQt5 attach data to QComboBox item

Is it possible to attach generic data to each QComboBox item so that I can retrieve it based on current selection?

I know I could build a dict with combo items as keys, but that is rather fragile as it will break on any item edit.

I seem to remember there's a way to attach custom data to almost anything in Qt, but I'm unable to find info (and I might be confusing with other frameworks; it's years I don't touch Qt).

I seem to understand I could dynamically add items using addItem(text, userData); can I do the same statically in Qt Designer?

Optimum would be to be able to attach data directly in Qt Designer and be able to retrieve it in currentIndexChanged handler.

Upvotes: 0

Views: 758

Answers (1)

musicamante
musicamante

Reputation: 48231

No, you can't set data "statically" in Designer, at least with the standard QComboBox control.

This is because the itemData() of an item can be any kind of data, and Qt natively supports a "limited" range of data types as QVariants, and while on PyQt it seems that any arbitrary type of data can be added the truth is that internally PyQt tries to convert recognized types to its own, and fall backs to a private PyQtObject to encapsule other things (python object subclasses).

There are some possibilities using promoted widgets or custom Designer plugins, but implementing a similar approach in the correct way is usually not worth it.

The basic rule is that on Qt you can only set widget properties (Qt properties, those listed in the "Properties" section of the documentation of each class), and for widgets that have internal models (like QComboBox or higher level views such as QListWidget) only the basic data roles are available: basically, the text and the icon, plus font/alignment, foreground/background, tooltip/whatsthis and flags/checkstate for item views.

Any other "property" (which are not actual properties) such as item data for custom roles can only be set programmatically.

If you want to have a more consistent access to item data in a QComboBox you can just use the dict to initialize it, and then access its model() (which by default is a QStandardItemModel), or, eventually, create a model on your own using the dict and use setModel.

Upvotes: 1

Related Questions