13.2.1.  QFileSystemModel

[ fromfile: qtmodelview.xml id: filesystemmodel ]

The QFileSystemModel can be viewed as a list, table or tree. Figure 13.5 shows one in a QTreeView.

Figure 13.5.  QFileSystemModel in a QTreeView

QFileSystemModel in a QTreeView

QFileSystemModel is already populated with data, so we can simply create one, create a view, and view->setModel(model). Example 13.1 shows what may be the simplest Qt model-view example.

Example 13.1. src/modelview/filesystem/main.cpp

#include <QtGui>
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    QFileSystemModel model;                
    model.setRootPath("/");           
    QTreeView tree;
    tree.setModel(&model);                 
    tree.setSortingEnabled(true);    1
    tree.header()->setResizeMode(QHeaderView::ResizeToContents);
    tree.resize(640, 480);
    tree.show();   
    return app.exec();
}

1

Enable HeaderView sort buttons.

<include src="src/modelview/filesystem/main.cpp" href="src/modelview/filesystem/main.cpp" id="filebrowser-main" allfiles="1" mode="cpp"/>


By setting the resizeMode in the headerView, the columns of the table or tree will be resized whenever the window is. These classes are the basic building blocks for writing a file browser widget.