c++ - 如何在 Qt 中的 QTableView 中显示一个简单的 QMap?

标签 c++ mysql qt user-interface qtableview

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

我见过几个例子,但它们都是针对一个只有一个字段的 vector 。他们使用另一个类来形成 View 。我想知道以前是否有人这样做过并且可以帮助我。

最佳答案

QMap 包装在 QAbstractTableModel 的子类中,并将其设置为 View 。下面是一个基本的功能示例:

文件“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);
// ...

它将显示一个表格 View ,填充如下:

enter image description here

关于c++ - 如何在 Qt 中的 QTableView 中显示一个简单的 QMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23484511/

相关文章:

php - 我想在我的网站上添加交互式日历

mysql - 如何在 mysql 中运行子查询

c++ - 从 'QChar' 转换为 'wchar_t'

c++ - 图形项的 QGraphicsScene 内的可拖动像素图

c++ - 多维数组的划分

c++ - 改进极小极大算法

c++ - OpenGL - 解释 glutInitDisplayMode()

c++ - 如何声明一个函数,它是一个类的成员并返回一个指向线程的函数指针?

php - sql insert - 神秘地破坏

c++ - QObject::connect: 无法连接 (null)::mySignal() 到 (null)::mySlot()