Qt - How to associate data with QTableWidgetItem?

强颜欢笑 提交于 2019-12-09 11:13:45

问题


I want to associate additional 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?


回答1:


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);



回答2:


You could derive from QTableItem and provide your own data member, or you could use the QTableView with your own model.



来源:https://stackoverflow.com/questions/2579579/qt-how-to-associate-data-with-qtablewidgetitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!