gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:02:03 27 4
gpt4 key购买 nike

我有一个名为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com