Qt-如何将数据与QTableWidgetItem相关联? [英] Qt - How to associate data with QTableWidgetItem?

查看:985
本文介绍了Qt-如何将数据与QTableWidgetItem相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将附加数据与插入到表中的每个QTableWidgetItem关联,以便将来在单击表项时使用该数据.但是这些数据应该不可见.我该怎么办?

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?

推荐答案

您可以使用

You can use QTableWidgetItem::setData() like so:

setData(Qt::UserRole, myData); // set

其中myData是受支持的 QVariant 类型.您可以使用QTableWidgetItem::data()来检索您存储的值.

Where myData is a supported QVariant type. You can use QTableWidgetItem::data() to retrieve the value that you store.

如果需要多个,则可以使用Qt::UserRole + 1 + 2,依此类推(Qt::UserRole是可用于特定于应用程序的目的的第一个角色.",您可以阅读有关的更多信息.其他类型的角色此处).

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

如果要存储QVariant本身不支持的自定义类型,则需要在Qt元对象系统中注册您的类型.请查看 QMetaType ,以获取更多详细信息.

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

这篇关于Qt-如何将数据与QTableWidgetItem相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆