• 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();
    }
  • 相关阅读:
    第六周活动进度表
    第二周活动进度表
    第一周活动进度表
    冲刺二阶段-个人总结10
    冲刺二阶段-个人总结09
    冲刺二阶段-个人总结08
    第一次冲刺-站立会议07
    第一次冲刺-站立会议06
    第一次冲刺-站立会议05
    第一次冲刺-站立会议04
  • 原文地址:https://www.cnblogs.com/billxyd/p/6916926.html
Copyright © 2020-2023  润新知