I want to associate aditional data with each QTableWidgetItem inserted into the table, in order to use that data in future, when it is being clicked on a table item. But that data should not be visible. How can I do that?
+4
A:
You can use QTableWidgetItem::setData()
like so:
setData(Qt::UserRole, myData); // set
Where myData
is a supported QVariant type. You can use QTableWidgetItem::data()
to retrieve the value that you store.
If you need more than one you can use Qt::UserRole
+ 1, + 2, and so on (Qt::UserRole
is "The first role that can be used for application-specific purposes.", you can read more about the other types of roles here).
If you're storing a custom type that isn't natively supported by QVariant you will need to register your type with the Qt meta-object system. Look at QMetaType for more details on that.
If you wanted to store an integer, for example:
QTableWidgetItem* widgetItem = tableWidget->item(row, col); // get the item at row, col
int myInteger = 42;
widgetItem->setData(Qt::UserRole, myInteger);
// ...
myInteger = widgetItem->data(Qt::UserRole);
richardwb
2010-04-05 16:48:47
Better answer !
Martin Beckett
2010-04-05 16:50:29
How can I associate an integer to table item with setData() function? Should I do following: item.setData(Qt::UserRole, myInteger)?
Narek
2010-04-05 17:02:22
I changed the example to be more clear, hope it helps.
richardwb
2010-04-05 17:05:19
Thank you very much! I have used this function bu with other Qt Roles and effect was not what I want so I got confused! Thanks!
Narek
2010-04-05 17:07:42
If you are adding more than 2 data elements to each table item, it starts to get easier to create a model and use QTableView instead, IMO.
Caleb Huitt - cjhuitt
2010-04-06 15:06:33
+3
A:
You could derive from QTableItem and provide your own data member, or you could use the QTableView with your own model.
Martin Beckett
2010-04-05 16:49:35
From my experience this is much more flexible than setData data Qt functions
penguinpower
2010-04-06 06:14:24
Yes but richard's answer is probably easier for a beginner - or if you are just trying to translate some MFC code
Martin Beckett
2010-04-06 14:55:54