PDA

View Full Version : Associate userData to items added to a QListWidget.



schall_l
3rd August 2009, 16:07
Hi,

I have a Dialog implementing 2 QListWidgets.
The lists are filled before the dialog is executed, and in order to make it convivial for the user I am setting the lists whith strings that are user friendly f.e.:
0x1234/4660 - Engine 1 speed indication
0x1333/4915 - Engine 1 temperature
...
...
The user can then drag and drop between the 2 lists.
When the widget is closed I would like to get what is in both lists.

I am wondering what would be the best way to associate userData to each item placed in the lists (somehow like what is possible with QComboBox::addItem(const QString & text, const QVariant & userData = QVariant()).

In such a case, the post treatment would be easier for me. I would then just itterate through the lists in order to get the userDatas composing each list instead of the user friendly string.

spirit
3rd August 2009, 16:26
did you try to use QListWidgetItem::setData?

schall_l
3rd August 2009, 16:30
Thank you, I guess this could work for me.
I'll post some sample code later.

schall_l
4th August 2009, 12:24
This is the code that worked for me thanks to the reply from Spirit.

The displayed text in the list widget is the one passed via QString description, while the 'internal' representation of the data is the one passed via unsigned int id. The 'internal' representation is stored via setData using the UserRole and is later on retrieved via the data function.


void FilterDialog::addIdentifer(QString description, unsigned int id) {
QListWidgetItem *item = new QListWidgetItem(description, listA);
item->setData(Qt::UserRole, id);
listA->addItem(item);
}

QList<unsigned int> FilterDialog::getIdentifiers() {
QList<unsigned int> tmp;
for (int i=0; i<listA->count(); i++) {
tmp.append( listA->item(i)->data(Qt::UserRole).toUInt() );
}
return tmp;
}