10.model/view实例(1)

1.如图显示一个2x3的表格:

    

 

 

思考:

1.QTableView显示这个表

2.QAbstractTableModel作为模型类。

3.文档中找到subclass的描述

When subclassing QAbstractTableModel, you must implement rowCount(), columnCount(), and data(). Default implementations of the index() and parent() functions are provided by QAbstractTableModel. Well behaved models will also implement headerData().

我们只需要实现rowCount(),columnCount(),data()函数。

 

代码如下:

mymodel.h

#ifndef MYMODEL_H
#define MYMODEL_H

#include <QAbstractTableModel>



class MyModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    explicit MyModel(QObject *parent = 0);
    QVariant data(const QModelIndex &index, int role) const;
    int rowCount(const QModelIndex &parent) const;
    int columnCount(const QModelIndex &parent) const;
signals:
    
public slots:
    
};

#endif // MYMODEL_H

mymodel.cpp

#include "mymodel.h"

MyModel::MyModel(QObject *parent) :
    QAbstractTableModel(parent)
{
}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::DisplayRole) {
        return QString ("row%1,col%2").arg(index.row()+1).arg(index.column()+1);
    }

    return QVariant();
}

int MyModel::rowCount(const QModelIndex &parent) const
{
    return 2;
}

int MyModel::columnCount(const QModelIndex &parent) const
{
    return 3;
}

main.cpp

#include "mymodel.h"

#include <QApplication>
#include <QTableView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTableView *view = new QTableView;
    MyModel *model = new MyModel;

    view->setModel(model);
    view->show();


    return a.exec();
}

 

posted @ 2017-05-28 22:56  billxyd  阅读(377)  评论(0编辑  收藏  举报