首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用代理将虚拟列添加到Qt模型

使用代理将虚拟列添加到Qt模型
EN

Stack Overflow用户
提问于 2016-09-14 13:52:59
回答 2查看 1.4K关注 0票数 4

我使用QSqlTableModel.在视图中显示SQL表。

我希望根据行数据显示额外的状态列,因为我使用自定义的QIdentityProxyModel,其中增加了QSqlTableModel.中不存在的新虚拟列的columnCount并返回数据。

代码语言:javascript
复制
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 (),我错过了什么?此外,头数据对我的额外列工作良好,问题只是与数据有关。视图会绘制额外的列,但是内容是空的(甚至没有绘制交替行背景)。太棒了!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-19 12:37:21

视图需要获取虚拟列的QModelIndex对象,因此我还需要重写代理中的index函数:

代码语言:javascript
复制
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不允许指定父表。

票数 4
EN

Stack Overflow用户

发布于 2016-09-14 15:01:20

m_mySqlTableColumnCount成员是不必要的。您必须通过监听源模型更新列计数的信号来确保它总是正确的。唉,这是不必要的。您希望将列计数请求传递到源模型:

代码语言:javascript
复制
int MyProxyModel::columnCount(const QModelIndex& parent) const
{
    return sourceModel() ? (QIdentityProxyModel::columnCount() + 1) : 0;
}

然后:

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39492264

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档