How to subclass QStandardItemModel to use my own Item type?

微笑、不失礼 提交于 2019-12-08 06:56:45

问题


How do I subclass QStandardItemModel to use my own Item type (e.g. MyItem instead of QStandardItem)? I mean I know I have to create a class and inherit QStandardItemModel but what next? How do I make it use MyItem everywhere? And yes, MyItem inherits after QStandardItem.


回答1:


I think it is impossible. You can subclass QAbstractItemModel to implement a model that use your item class.

Also you can use default QStandardItemModel and add your additional object to items using QStandardItem::setData. Since it accepts QVariant, you can put any value in it, event QSharedPointer (you need to register appropriate meta type).




回答2:


You don't need to subclass model, just item class. All you need is this:

class YourItem : public QStandardItem
{
// ...
public:
       virtual QStandardItem *clone() const;
};

QStandardItem *YourItem::clone() const
{
    return new YourItem(/*your constructor parameters to copy data if needed*/);
}

when installing model:

model->setItemPrototype(new MyItem());
ui->listView->setModel(model);


来源:https://stackoverflow.com/questions/17050573/how-to-subclass-qstandarditemmodel-to-use-my-own-item-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!