2014-02-19 36 views
2

在下面的示例中,尽管应该有2列,但每个子项都只有1列。树视图列计数的混淆

(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; 
    } 
} 

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

+2

我猜'QTreeView'根据根项目值检测所需的列数。出于性能原因,它不能遍历整个树来检测列数。验证它的最佳方法是选择'QTreeView'的源代码。 –

+0

@MarekR是100%的权利。列计数仅为根项目计算。如果你在任何一行中都需要较少的列 - 只需不填充它们并在:: index –

+0

@Marek R中返回无效的QModelIndex它会遍历整个树来检测列数(我使用断点检查它)。但是它不会调用MyTreeModel中的数据(..)函数来获取大于父列数 – SRF

回答

2

我检查的源代码在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 

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

+0

更新位置的列:https://github.com/qtproject/qtbase/blob/dev/src/widgets/itemviews/qheaderview .cpp#L1826 –

+0

我更新了链接 –