正如@André所说,依赖于QMap
的keys()
和values()
方法的解决方案根本不高效,不应该使用。
相反,您应该使用迭代器!
因此,使用相同的.h文件
#ifndef MAPMODEL_H
#define MAPMODEL_H
#include <QAbstractTableModel>
#include <QMap>
class MapModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum MapRoles {
KeyRole = Qt::UserRole + 1,
ValueRole
};
explicit MapModel(QObject *parent = 0);
int rowCount(const QModelIndex& parent = QModelIndex()) const;
int columnCount(const QModelIndex& parent = QModelIndex()) const;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
void setMap(QMap<int, QString>* map);
private:
QMap<int, QString>* _map;
};
#endif
这个CPP代码大概是这样的:
#include "mapmodel.h"
MapModel::MapModel(QObject *parent) :
QAbstractTableModel(parent), _map(nullptr)
{}
void MapModel::setMap(QMap<int, QString>* map)
{
beginModelReset();
_map = map;
endModelReset();
}
int MapModel::rowCount(const QModelIndex& parent) const
{
if (_map)
return _map->count();
return 0;
}
int MapModel::columnCount(const QModelIndex & parent) const
{
return 2;
}
QVariant MapModel::data(const QModelIndex& index, int role) const
{
if (!_map || !index.isValid() || index.row() >= _map->count() || role != Qt::DisplayRole)
return QVariant();
auto it = _map.cbegin();
it += index.row();
if (index.column() == 0)
return it.key();
if (index.column() == 1)
return it.value();
return QVariant();
}
主要变化在于
MapModel::data
中使用了迭代器,正如@Claudiu所评论的那样,在
MapModel::setMap
中必须使用
beginModelReset
和
endModelReset
(以允许您能够更改模型上的地图并向视图发出信号)。
如果您需要一些示例,我已经为
FamilyModel2
上的
QAbstractListModel
完成了这项工作。这是
头文件,
cpp文件。它使用一个地图的包装器,您可以在
这里找到。
请检查构造函数
FamilyModel2::FamilyModel2
,其中连接了外部信号以管理条目的插入,并在数据更新时发出
dataChanged
信号;)
setMap
函数中,你需要执行beginModelReset()
和endModelReset()
来重置模型。 - Claudiu