使用代理向Qt SQL模型添加虚拟列
Add virtual column to Qt SQL model using a proxy
我使用QSqlTableModel在视图中显示一个SQL表。
我想根据行数据显示一个额外的状态列,为此我使用自定义QIdentityProxyModel,其中我增加columnCount并返回数据为新的虚拟列,不存在于QSqlTableModel。
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);
}
编辑:我改变了一些更简单的关于注释的代码。我还是有同样的问题
我的问题是,视图从来没有问我的虚拟列的数据,它调用data()为实际SQL表的所有其他列,但不是最后一个虚拟的,我错过了什么?此外,标题数据对于我的额外列来说工作得很好,问题只在于数据。视图绘制额外的列,但内容为空(即使交替行背景也不会绘制)。谢谢!
视图需要获取虚拟列的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不允许指定父
不需要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);
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何在Qt中合并/追加/添加两个用于线程的模型?
- 添加新纹理OpenGL时,模型消失了
- 如何使用 word 对象模型中的C++接口在 word 中添加自定义 XML 艺术
- QML ListView将新行添加到模型中的子向量
- 在我的模型DirectX11中添加纹理的问题
- 如何在CPLEX上将多维IloRangeArray添加到模型中
- 添加行的 gtkmm 树模型
- 我正在寻找一种在从模型中删除并重新添加修改后的可提取对象后操作 iloextract 对象的方法
- 在C++中为CPLEX模型添加约束
- 在向模型添加新数据后,QML TreeView没有在运行时更新
- Qt QTreeView添加到模型时不更新
- 在使用Gurobi向模型添加约束时会遇到麻烦
- 使用代理向Qt SQL模型添加虚拟列
- 在QTableView的自定义模型中添加和删除项目