qt把map中的值插入到tableView
时间: 2024-04-10 15:27:35 浏览: 112
QT的TableView实现多级表头
要将`map`中的值插入到`QTableView`中,你需要创建一个自定义的`QAbstractTableModel`子类,并将其作为数据模型。以下是一个示例代码,演示了如何将`map`中的值插入到`QTableView`中:
```cpp
#include <QApplication>
#include <QTableView>
#include <QAbstractTableModel>
#include <QMap>
class MapTableModel : public QAbstractTableModel
{
public:
explicit MapTableModel(const QMap<QString, QVariant>& map, QObject* parent = nullptr)
: QAbstractTableModel(parent), m_map(map)
{
}
int rowCount(const QModelIndex& parent = QModelIndex()) const override
{
Q_UNUSED(parent)
return m_map.size();
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override
{
Q_UNUSED(parent)
return 2; // Assuming two columns: key value
}
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole)
{
if (index.column() == 0) // Key column
return m_map.keys().at(index.row());
else if (index.column() == 1) // Value column
return m_map.values().at(index.row());
}
return QVariant();
}
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
{
if (section == 0)
return QStringLiteral("Key");
else if (section == 1)
return QStringLiteral("Value");
}
return
阅读全文