2015-04-16 48 views
0

我正在使用QTreeView和QFileSystemModel。我想要只有根可擴展,顯示1級子目錄,就是這樣,子目錄應該只能選擇,但不能擴展。任何指導如何我可以將此存檔?QTreeView QFileSystemModel - 限制只能擴展到根

謝謝。

+1

您可以創建做它的過濾代理模型。視圖不需要更改。 –

回答

1

正如前面所說,你可以創建一個代理模型修改模型的行爲:

class Proxy : public QSortFilterProxyModel { 
public: 
    static int indexLevel(QModelIndex index) { 
    int level = 0; 
    while(index.parent().isValid()) { 
     level++; 
     index = index.parent(); 
    } 
    return level; 
    } 

    int rowCount(const QModelIndex& parent) const { 
    if (indexLevel(parent) > 0) { 
     return 0; 
    } 
    return QSortFilterProxyModel::rowCount(parent); 
    } 

    bool hasChildren(const QModelIndex& parent) const { 
    if (indexLevel(parent) > 0) { 
     return false; 
    } 
    return QSortFilterProxyModel::hasChildren(parent); 
    } 
}; 

//... 
QFileSystemModel model; 
model.setRootPath(QString()); 
Proxy proxy; 
proxy.setSourceModel(&model); 
QTreeView view; 
view.setModel(&proxy); 
view.show(); 
相關問題