Qt - 如何将数据与 QTableWidgetItem 关联?

发布于 2024-08-27 17:34:32 字数 84 浏览 4 评论 0原文

我想将附加数据与插入表中的每个 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我们只是彼此的过ke 2024-09-03 17:34:32

您可以使用 QTableWidgetItem::setData() 像这样:

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

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

如果您需要多个角色,可以使用 Qt::UserRole + 1、+ 2 等(Qt::UserRole 是“可以使用的第一个角色”用于特定于应用程序的目的。”,您可以阅读有关其他类型角色的更多信息 这里)。

如果您要存储 QVariant 本身不支持的自定义类型,您将需要向 Qt 元对象系统注册您的类型。有关更多详细信息,请参阅 QMetaType

如果你想存储一个整数,例如:

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

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);
甜尕妞 2024-09-03 17:34:32

您可以从 QTableItem 派生并提供您自己的数据成员,或者您可以将 QTableView 与您自己的模型一起使用。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文