Sunday, April 3, 2011

Setting user data in Qt's widget items

If you use standard Qt widget such as QTreeWidget, QTableWidget or QListWidget, you may want to attach objects to the items. As an example, here's how to do it with QTreeWidgetItem (NOTE: the code is written from scratch to give you a rough idea, it may not compile correctly and is not optimised):

#include <QVariant>

QTreeWidgetItem* addApple() {
  Apple *apple = new Apple();
  QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, QStringList( ) );
  QVariant v;
  item->setData(0, Qt::UserRole, v); // attach apple to column 0

  return item;

Apple* getApple(QTreeWidgetItem *item) {
  QVariant v = item->data(0, Qt::UserRole); // get the data from column 0
  Apple *apple = v.value<Apple*>(); // convert the data to Apple*
  return apple;

/* The following line will cause a compile error since "const Apple *" 
     is different from "Apple *". If you want to use it, add 
     Q_DECLARE_METATYPE(const Apple*) to Apple.
  //const Apple *apple = v.value<Apple*>();

In Apple.h, you need to declare a metatype:

#include <QMetaType>

class Apple {