【问题标题】:Confusion of column count for tree views树视图的列数混淆
【发布时间】:2014-02-19 12:20:57
【问题描述】:

在下面的示例中,每个子项只有 1 列,尽管它应该有 2 列。

(MyTreeModel 是 QAbstractItemModel 的子类。)

int MyTreeModel::columnCount( const QModelIndex &rParent /*= QModelIndex()*/ ) const
{
    if (rParent.isValid())
    {
           return 2;
    }
    else
    {
        return 1;
    }
}

在以下示例中,QTreeView 按预期显示 2 列父项和 1 列子项。

int MyTreeModel::columnCount( const QModelIndex &rParent /*= QModelIndex()*/ ) const
{
    if (rParent.isValid())
    {
           return 1;
    }
    else
    {
        return 2;
    }
}

因此,似乎子项的列数受到其父项的列数的限制。这是标准行为吗?我是不是做错了什么?

【问题讨论】:

  • 我猜QTreeView 根据根项目值检测所需的列数。出于性能原因,它不能遍历整个树来检测列数。验证它的最佳方法是选择QTreeView 的源代码。
  • @MarekR 100% 正确。仅针对根项目计算列数。如果您在任何行中需要更少的列 - 只需不要填充它们并在 ::index 中返回无效的 QModelIndex
  • @Marek R 它确实遍历整个树以检测列数(我使用断点检查了它)。但它不会为大于父级列数的列调用 MyTreeModel 中的 data(..) 函数

标签: c++ qt


【解决方案1】:

我在https://qt.gitorious.org/查看了源代码(目前无法替代https://github.com/qtproject/qtbase/blob/dev/src/widgets/),找到了答案:

  1. 我检查了方法void QTreeView::setModel(QAbstractItemModel *model)。在那里我注意到d->header->setModel(model); 行。标题是您需要的。
  2. Type of header,是QHeaderView
  3. 然后我检查了方法void QHeaderView::setModel(QAbstractItemModel *model)
  4. 已建立连接:QObject::disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(sectionsInserted(QModelIndex,int,int)));
  5. 我做的最后一件事是读取槽方法void QHeaderView::sectionsInserted(const QModelIndex &parent, int logicalFirst, int logicalLast)

猜猜我在那里找到了什么:

void QHeaderView::sectionsInserted(const QModelIndex &parent,
int logicalFirst, int logicalLast)
{
    Q_D(QHeaderView);
    if (parent != d->root)
        return; // we only handle changes in the top level

所以只有顶级项目对列数有影响。

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 2019-07-15
  • 2012-05-19
  • 2023-03-28
  • 2014-09-26
  • 2012-12-29
  • 2020-09-05
相关资源
最近更新 更多