【发布时间】:2011-04-19 05:59:55
【问题描述】:
我对 QAbstractTableModel 进行了子类化以表示来自 QMap 的数据。此 QMap 具有 QSqlRecords 的 QLists,并且此映射由我的代码的其他部分修改。我想将此模型与 QTableView 一起使用,以显示此映射中每个键的 sql 记录。这是我的代码。
//mymodel.h
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
MyModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
void setRecordMap(QMap<int, QList<QSqlRecord>> *map);
void setSelectedSerMsgIndex(QModelIndex *index);
private:
QMap<int, QList<QSqlRecord>> *recordMap;
QModelIndex *selectedSerendibMsgIndex;
};
//mymodel.cpp
MyModel::MyModel(QObject *parent) : QAbstractTableModel(parent)
{
}
int MyModel::rowCount(const QModelIndex &parent) const
{
if(recordMap->isEmpty())
return 0;
int row = selectedSerendibMsgIndex->row();
return recordMap->value(row).size();
}
int MyModel::columnCount(const QModelIndex &parent) const
{
if(recordMap->isEmpty())
return 0;
int row = selectedSerendibMsgIndex->row();
return recordMap->value(row).at(0).count();
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if(recordMap->isEmpty())
return QVariant();
if (!index.isValid())
return QVariant();
int row = selectedSerendibMsgIndex->row();
if (index.row() >= recordMap->value(row).size())
return QVariant();
if (role == Qt::DisplayRole)
{
return recordMap->value(row).value(index.row()).value(index.column()); /* QVariant("hello");*/
}
else
{
return QVariant();
}
}
void MyModel::setRecordMap(QMap<int, QList<QSqlRecord>> *map)
{
recordMap = map;
}
void MyModel::setSelectedSerMsgIndex(QModelIndex *index)
{
selectedSerendibMsgIndex = index;
}
抱歉,这篇文章太大了。但问题是,我看不到地图上的数据。我猜这是因为我的 data() 方法的实现有问题。但我无法弄清楚它是什么。请善待帮助我。谢谢。
【问题讨论】:
-
然后我会检查 rowCount 和 columnCount 是否返回预期值 (>0)。在 setRecordMap() 中替换地图后也调用 reset()。
-
当你按值传递map时,你传递给模型后map会改变吗?
-
另一件要检查的事情,只是为了确定:您是否在视图上设置了模型?
-
也不需要使用指向 QMap 的指针。不幸的是,我认为这不是问题所在。 :( 我建议委派给
QSqlTableModel或QSqlQueryModel而不是直接映射到QSqlRecord。索引、视图刷新和选择逻辑可能会中断。 -
kasper360:它不起作用,因为您无法观察地图的变化(没有通知机制)。当数据被插入/删除到地图中时,模型必须插入/删除行和列。您要么需要一个由模型控制的私有数据结构(请注意,使用地图效率相当低 - 您需要 O(1) 查找),或者需要来自外部的通知,说明共享地图已更改(以及如何更改)。
标签: qt subclassing qabstracttablemodel