Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Using UserData in Qt's list Widgets

From Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Emulator / desktop / device
Platform(s): All Qt Supported
Keywords: QComboBox, Qt::UserRole,
Created: Avis (30 Nov 2010)
Last edited: hamishwillee (11 Oct 2012)


This example shows how to store and use UserData in Qt's list Widgets like QComboBox and others. A combo box can be used to show the current items like a list widget.

Usually we operate with pairs of values - visible text data and hidden value, bounded to that text (something like ID, for example). Let's see how this works.


#include <QComboBox>


First of all let's fill the list.

// get the refence to QComboBox for filling
void MainWindow::fillBox(QComboBox* &aBox)
// text value - visible to User
QString aStringValue;
// hidden Int value - string ID
int id;
// filling loop
for (int i = 0; i< 100; i++)
id = i+1;
aStringValue = QString("Value number %1").arg(QString::number(id));
// first param - caption of Item, second param - user Data of any type
aBox->addItem(aStringValue, id);

Function, searching and activating Item with ID = aID

// get the refence to QComboBox and value of ID to find
void MainWindow::findById(const int aID, QComboBox* &aBox)
// find the number of item by it's hidden UserValue
int i = aBox->findData(aID, int(Qt::UserRole)); // value of hidden param is treated as INT
// set founded item to be current

Now, if we want to show in ComboBox line with attribute ID = 56, just call the search function


--Avis 13:04, 30 November 2010 (UTC)

This page was last modified on 11 October 2012, at 01:18.
90 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.