10.model/view实例(3)

任务:3x2的表格,第一个单元格显示当前时间

      

思考:

1.data函数里面QTime::currentTime()显示当前时间

2.但是这个事件是一个固定的时间,不会变动

3.需要时间变动,View就得每秒中都从Model中调用data函数。

4.这里就需要定时器。

5.定时器每秒发射1个信号。这个信号告诉View。Model中数据变了,你需要重新调用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:
    
private slots:
    void dataChange();
};

#endif // MYMODEL_H

mymodel.cpp

#include "mymodel.h"

#include <QTime>
#include <QTimer>
#include <QModelIndex>

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

    QTimer *timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();

    connect(timer, SIGNAL(timeout()), this, SLOT(dataChange()));
}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    int col = index.column();

    if(role == Qt::DisplayRole) {
        if(row == 0 && col == 0)
            return QTime::currentTime();

    }

    return QVariant();
}

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

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

void MyModel::dataChange()
{
    QModelIndex index = createIndex(0, 0);
    emit dataChanged(index, index);
}

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();
}
原文地址:https://www.cnblogs.com/billxyd/p/6917131.html