如何在Qt的QTableView中显示简单的QMap?

时间:2014-05-06 01:22:21

标签: c++ mysql qt user-interface qtableview

我有QMap名为map。我用我的数据库中的几行数据初始化了这个map。现在我将此map发送到另一个包含GUI类的类。在我的GUI中,我有一个TableView项。我需要在此TableView中以任何顺序显示此map

我见过几个例子,但它们都是一个只有一个字段的矢量。他们使用另一个类来形成视图。我想知道是否有人之前已经这样做过,可以帮助我。

1 个答案:

答案 0 :(得分:9)

QMap包裹在QAbstractTableModel的子类中并将其设置为视图。以下是一个基本的功能示例:

文件“mapmodel.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;
    inline void setMap(QMap<int, QString>* map) { _map = map; }

private:
    QMap<int, QString>* _map;
};

#endif // MAPMODEL_H

档案“mapmodel.cpp”

#include "mapmodel.h"

MapModel::MapModel(QObject *parent) :
    QAbstractTableModel(parent)
{
    _map = NULL;
}

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)
        return QVariant();
    if (index.row() < 0 ||
        index.row() >= _map->count() ||
        role != Qt::DisplayRole) {
        return QVariant();
    }
    if (index.column() == 0)
        return _map->keys().at(index.row());
    if (index.column() == 1)
        return _map->values().at(index.row());
    return QVariant();
}

使用示例:

// ...
QMap<int, QString> map;
map.insert(1, "value 1");
map.insert(2, "value 2");
map.insert(3, "value 3");

MapModel mapmodel;
mapmodel.setMap(&map);

YourTableView.setModel(&mapmodel);
// ...

它将显示填充如下的表格视图:

enter image description here

相关问题