c++ - 使用代理向 Qt SQL 模型添加虚拟列

标签 c++ qt

我使用 QSqlTableModel 在 View 中显示 SQL 表。

我想根据行数据显示一个额外的状态列,为此我使用自定义 QIdentityProxyModel,我在其中增加了 columnCount 并返回了 data 用于 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);
}

编辑: 我更改了代码以获得与注释相关的更简单的内容。我仍然有同样的问题。

我的问题是 View 从不为我的虚拟列请求数据,它为实际 SQL 表的所有其他列调用 data() 但不是最后一个虚拟列,我错过了什么? 此外,标题数据对我的额外列运行良好,问题仅在于数据。 View 绘制额外的列,但内容为空(甚至不绘制交替行背景)。 谢谢!

最佳答案

View 需要获取虚拟列的 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 不允许指定父级。

关于c++ - 使用代理向 Qt SQL 模型添加虚拟列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39492264/

相关文章:

c++ - 显示列表最适合这个吗? (OpenGL)

c++ - 在没有 netbeans 的情况下运行 C++ netbeans 项目

c++ - 使用自定义小部件自定义 QT QTreeView

c++ - Qt 将应用程序对齐到屏幕的左上角

c++ - 控制台上的 Qt 应用程序文本流

c++ - WriteFile() block (通过命名管道从 C++ 客户端写入到 C# 服务器)

c++ - Qt、QTransform旋转

macos - 将/usr/local/bin (homebrew) 添加到 Mac OSX 上 pkg-config 的 QtCreator 搜索路径

python - 挂起当前函数直到对话框关闭

c++ - 如何用 QStringList 填充 ListView ?