TreeView的用法,生成文件目录树

时间:2022-07-29 12:34:38

还想着自己通过QDir 实现将一个目录下的文件夹和文件显示到TreeView 中。。

哪知QT本身就有这样的类QDirModel,只需下面三行代码!

    QDirModel *model = new QDirModel;
ui->treeView->setModel(model);
ui->treeView->setRootIndex(model->index("./"));


扩展:

    model = new QDirModel;
model->setSorting(QDir::Name);

ui->treeView->setModel(model);
ui->treeView->setRootIndex(model->index("./"));
ui->treeView->setColumnHidden(1,true);
ui->treeView->setColumnHidden(2,true);
ui->treeView->setColumnHidden(3,true);
//隐藏其它列信息;

QSize a(0,0);
ui->treeView->setIconSize(a);
//隐藏图标

ui->treeView->header()->setStretchLastSection(true);
ui->treeView->header()->setSortIndicator(0, Qt::AscendingOrder);
ui->treeView->header()->setSortIndicatorShown(true);
ui->treeView->header()->setClickable(true);

QModelIndex index = model->index("./");
ui->treeView->expand(index);
ui->treeView->scrollTo(index);
ui->treeView->resizeColumnToContents(0);
ui->treeView->expandAll();
//默认全部展开


// ui->treeView->setHeaderHidden(TRUE);
ui->treeView->setEditTriggers(0);

ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);