2014-02-19 37 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

我更新了鏈接 –