PDA

View Full Version : Two QStandardItem objects handling different attributes of same object



jmborr
22nd February 2017, 19:16
I'm a newbie with the Model/View programming of Qt and have read the Editable Tree Model Example in the Qt documentation. In this example 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().

I 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, one to edit/display m_name and another to edit/display m_description. Is there some standard design scheme to manage a single Foo object in memory while having more than one QStandardItem object to handle different attributes of Foo?

ChrisW67
22nd February 2017, 21:21
No, but you can subclass QAbstractTableModel to get much of the table handling logic for free and still have your own internal data structure.

jmborr
22nd February 2017, 22:38
I just found a post in qtcentre (http://www.qtcentre.org/threads/67512-Hierarchical-disparate-data-structure-and-MVD-(QStandardItemModel-QTreeView)?highlight=qstandarditemodel+tree) suggested Chapter 4 of Advanced Qt Programming (https://www.amazon.com/gp/product/0321635906?pldnSite=1) and lo and behold, there's a discussion of a tree subsclassing QstandardItemModel and QStandardItem where each row of the tree is made up of three QstandardItem objects handling different properties of a single object.
The implementation source code is freely available (https://www.qtrac.eu/aqpbook.html)

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

anda_skoa
23rd February 2017, 08:36
Sounds like you would rather want a custom model that operates on your Foo objects.

Cheers,
_