ModelView3:ChangingModel
ModelView系列的第三篇:在前两篇的基础上,通过创建自定义model,掌握更新model内容的方法。
前置实例
实例位置
Qt_Offical_demo/widgets/tutorials/modelview
运行效果
效果:
- 创建两行三列的model和view;
- 实时更新表格中内容的方法;
代码分析
大部分代码与ModelView1:readonly的相同,唯一不同的自定义的model类MyModel
,这里列出:
Class MyModel
一个自定义的model,实现实时更新
mymodel.h
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
MyModel(QObject *parent);
int rowCount(const QModelIndex &parent = QModelIndex()) const override ;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QTimer *timer;
private:
int selectedCell;
private slots:
void timerHit();
};
与ModelView1:readonly的相同基本相同,多出来一个QTimer
、私有成员int selectedCell
和槽函数void timerHit()
。
具体的作用,在后面介绍。
MyModel::MyModel(QObject *parent)
:QAbstractTableModel(parent)
{
//Info 1
timer = new QTimer(this);
timer->setInterval(1000);
connect(timer, SIGNAL(timeout()) , this, SLOT(timerHit()));
timer->start();
}
int MyModel::rowCount(const QModelIndex & /*parent */) const
{
return 2;
}
int MyModel::columnCount(const QModelIndex & /*parent */) const
{
return 3;
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
//Info 2
int row = index.row();
int col = index.column();
if (role == Qt::DisplayRole)
{
if (row == 0 && col == 0)
{
return QTime::currentTime().toString();
}
}
return QVariant();
}
//! [quoting mymodel_QVariant ]
//-------------------------------------------------------
//! [quoting mymodel_b ]
void MyModel::timerHit()
{
//we identify the top left cell
QModelIndex topLeft = createIndex(0,0);
//emit a signal to make the view reread identified data
emit dataChanged(topLeft, topLeft);
}
Info 1:
定时器的用法
//创建定时器
timer = new QTimer(this);
//设置定时周期1000ms,即1s
timer->setInterval(1000);
// 创建信号槽,定时结束后跳转到槽函数timerHit()
connect(timer, SIGNAL(timeout()) , this, SLOT(timerHit()));
// 开始定时器
timer->start();
定时器连接到一个槽函数timerHit()
:
void MyModel::timerHit()
{
//获取模型表格最左上角的那一栏的索引值
QModelIndex topLeft = createIndex(0,0);
//Info 1.1
emit dataChanged(topLeft, topLeft);
}
Info 1.1
```datachanged()``函数的原型为:
QAbstractItemModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int> ())
第一个参数是左上角的索引;第二个参数是右下角的索引;第三个参数是角色容器。一般只是用前两个参数。信号的意义是发送数据改变的信号,此后data()
会被自动调用,相应的索引会作为参数传递。
Info 2:
注意data()函数的写法是具有一定固定套路的。要熟悉return QVariant()
这个用法。
其中的return QTime::currentTime().toString();
是返回系统当前时间的是个字符串。
分析
- 通过定时器发送datachange()信号,实时更新模型中的数据;
- 掌握定时器的常规用
进阶实例
- 无