1
votes

I was wondering how I could set a 'tag' on items/rows/columns on a QTableWidgetItem. For exmaple, in C# it is called a tag on the Listview. I need this because I need to link an item to each row.

ListViewItem.Tag = myObject;

Thanks for any help.

1

1 Answers

3
votes

This would be accomplished using QTableWidgetItem::setData() and a bit of QVariant magic. For example:

// Allow your object type to be converted to a QVariant:
Q_DECLARE_METATYPE( ObjectType* );

// Define a role to store your object under:
const int ObjectRole = Qt::UserRole + 1;

QTableWidgetItem *item = new QTableWidgetItem();
item->setData( ObjectRole, QVariant::fromValue(myObject) );

and then to retrieve your object:

ObjectType *myObject = item->data( ObjectRole ).value<ObjectType*>();

Easy right? ;)

See also: Q_DECLARE_METATYPE, QVariant::fromValue(), QVariant::value()