我使用QSqlTableModel.在视图中显示SQL表。
我希望根据行数据显示额外的状态列,因为我使用自定义的QIdentityProxyModel,其中增加了QSqlTableModel.中不存在的新虚拟列的columnCount并返回数据。
int MyProxyModel::columnCount(const QModelIndex& parent) const
{
return sourceModel() ? (sourceModel()->columnCount() + 1) : 0;
}
QVariant MyProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section == columnCount()-1 &&
orientation == Qt::Horizontal &&
role == Qt::DisplayRole)
{
return tr("MyHeader");
}
return QIdentityProxyModel::headerData(section, orientation, role);
}
QVariant MyProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
qDebug() << "data " << proxyIndex.row() << proxyIndex.column();
// ...never called for my extra column (== columnCount()-1)
if (proxyIndex.column() == columnCount()-1 && role == Qt::DisplayRole)
return QString("I am virtual");
return QIdentityProxyModel::data(proxyIndex, role);
}编辑:,我更改了代码,以便对注释进行更简单的处理。我还是有同样的问题。
我的问题是,视图从不为我的虚拟列请求数据,它为实际SQL表的所有其他列调用data(),而不是为最后一个虚拟列调用data (),我错过了什么?此外,头数据对我的额外列工作良好,问题只是与数据有关。视图会绘制额外的列,但是内容是空的(甚至没有绘制交替行背景)。太棒了!
发布于 2016-09-19 12:37:21
视图需要获取虚拟列的QModelIndex对象,因此我还需要重写代理中的index函数:
QModelIndex MyProxyModel::index(int row, int column, const QModelIndex &parent) const
{
if (column == columnCount()-1)
return createIndex(row, column);
return QIdentityProxyModel::index(row, column);
}我不介意父表,因为我只有一个表(来自数据库),但我不知道在需要时如何处理它,因为createIndex不允许指定父表。
发布于 2016-09-14 15:01:20
m_mySqlTableColumnCount成员是不必要的。您必须通过监听源模型更新列计数的信号来确保它总是正确的。唉,这是不必要的。您希望将列计数请求传递到源模型:
int MyProxyModel::columnCount(const QModelIndex& parent) const
{
return sourceModel() ? (QIdentityProxyModel::columnCount() + 1) : 0;
}然后:
QVariant MyProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (section == columnCount()-1 &&
orientation == Qt::Horizontal &&
role == Qt::DisplayRole)
{
return tr("MyHeader");
}
return QIdentityProxyModel::headerData(section, orientation, role);
}
QVariant MyProxyModel::data(const QModelIndex &proxyIndex, int role) const
{
if (proxyIndex.column() == columnCount()-1) {
qDebug() << proxyIndex.row() << proxyIndex.column();
...
}
return QIdentityProxyModel::data(proxyIndex, role);
}https://stackoverflow.com/questions/39492264
复制相似问题