Search code examples
c++qtviewqtreeview

How to Get Absolute Path of Currently Selected Item in QTreeView


I have a simple QTreeView with a QFileSystemModel pointing to the root directory:

#include "mainwindow.h"
#include <QApplication>
#include <QFileSystemModel>
#include <QtGui/QApplication>
#include <QtGui>
#include <QTreeView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QFileSystemModel *model = new QFileSystemModel;
    QString dir("/");
    model->setRootPath(dir);
    QTreeView *tree = new QTreeView();
    tree->setModel(model);
    tree->setRootIndex(model->index((dir)));
    tree->show();
    return a.exec();
}

It displays something like this: enter image description here

The item I have selected above is /usr/lib/clang. How can I get the absolute path of the currently selected item?


Solution

  • Use view->selectionModel()->selectedIndexes() to obtain selected indexes and fileSystemModel->filePath() to get path for these indexes.