I'm a newbie with the Model/View programming of Qt and have read the Editable Tree Model Example in the Qt documentation. The nice feature in this example is that a single object (TreeItem
) encapsulates two pieces of information that later are displayed in a single row containing two columns (name
and description
) thanks to overriding of QModelIndex QAbstractItemModel::index
and QVariant QAbstractItemModel::data
.
Now, I also have a custom class (e.g. Foo
) containing two pieces of information (Foo::m_name
and Foo::m_description
) that I want to display in a single row containing two columns, but instead of subclassing QAbstractItemModel
I want to subclass QStandardItemModel
because it has some much functionality. However, it seems I must create two QStandardItem
objects for each of my Foo
objects, one to handle m_name
and another to handle m_description
. How can I keep a single Foo
object in memory and have these two QStandardItem
objects refer to it?
In my question there's the implicit assumption that one must create a QStandardItem
object for each (row, column) pair. Please let me know if this is wrong.
A post in qtcentre suggested Chapter 4 of Advanced Qt Programming and lo and behold, there's a discussion of a tree subsclassing QstandardItemModel
and QStandardIteml
where each row of the tree is made up of three QstandardItem
handling different properties of a single object.
The implementation source code is freely available
Basically, one has:
class myItem : public QStandardItem {
public:
myItem(Foo &afoo) : QStandardItem(afoo.getName()), m_foo(afoo) {
m_description = new QStandardItem(afoo.getDescription());
}
QstandardItem *m_description; // display m_description
private:
Foo &m_foo;
};
and then we insert a row of two QstandardItem in our model tree
class myModel: public QStandardItemModel {
StandardItem *myModel::appendRow(QStandardItem *parent, Foo &afoo)
{
auto *doublet = new myItem(afoo);
parent->appendRow(QList<QStandardItem*>() << doublet
<< double->m_description);
return nameItem;
}
}