树视图的列数混淆

SRF*_*SRF 6 c++ qt

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

(MyTreeModel是QAbstractItemModel的子类.)

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

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

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

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

Mar*_*k R 5

我在https://qt.gitorious.org/上检查了源代码(当前无法正常使用https://github.com/qtproject/qtbase/blob/dev/src/widgets/),找到了以下答案:

  1. 我检查了方法void QTreeView::setModel(QAbstractItemModel *model)。在那里我注意到了d->header->setModel(model);。标头是您所需要的。
  2. 标头类型QHeaderView
  3. 然后我检查了方法 void QHeaderView::setModel(QAbstractItemModel *model)
  4. 建立连接: QObject::disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(sectionsInserted(QModelIndex,int,int)));
  5. 我做的最后一件事是阅读slot方法 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
Run Code Online (Sandbox Code Playgroud)

因此,只有顶级项目才会影响列数。