QAbstractTableModel retrieve custom object on data changed

独自空忆成欢 提交于 2019-12-04 20:11:51

You can create custom type compatible with QVariant using the macro Q_DECLARE_METATYPE. If you declare your class as a metatype, you can store it in a QVariant and extract it with a cast.

Here an example that show how to create a custom delegate which can display data from a custom class using QVariant :

class Data {
private:
    QString name;
    int value;
public:
    Data() : name(""), value(-1){}
    Data( QString n, int v ) : name(n), value(v){}
    QString text() {
        return QString( "Test %1 - %2" ).arg( name ).arg( value );
    }
};

Q_DECLARE_METATYPE( Data )

class Delegate : public QStyledItemDelegate {
protected:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        Data d = index.data().value<Data>();
        painter->drawText( option.rect, d.text() );
    }
};


int main( int argc, char **argv) {
    QApplication app(argc, argv, true);

    QVariant var0, var1, var2;
    var0.setValue(Data( "Item A", 0 ));
    var1.setValue(Data( "Item B", 1 ));
    var2.setValue(Data( "Item C", 2 ));

    QListView *view = new QListView();
    QStandardItemModel model(3, 1);

    model.setData( model.index( 0, 0 ), var0 );
    model.setData( model.index( 1, 0 ), var1 );
    model.setData( model.index( 2, 0 ), var2 );
    view->setModel( &model );
    view->show();
    view->setItemDelegate( new Delegate() );
    return app.exec();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!