问题
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