Question

When I start the program, the filedialog is in a certain directory. Then I move to other directories and select some files. Once the files are selected I try to get that current directory from which the files are selected. But it doesn't return me the current directory, it returns me the original directory which the filedialog was initially in when the program was started. The code snippet is as below:

QFileDialog * fileDialog = new QFileDialog(this);
fileDialog->setFileMode(QFileDialog::ExistingFiles);
QListView* list = fileDialog->findChild<QListView*>("listView");
if(list)
{
    list->setSelectionMode(QAbstractItemView::MultiSelection);
}
QTreeView* tree = fileDialog->findChild<QTreeView*>();
if(tree)
{
    tree->setSelectionMode(QAbstractItemView::MultiSelection);
}
if(fileDialog->exec())
{
    if(fileDialog->selectedFiles().size()>0)
    {
        QDir dir = fileDialog->directory();
        fileDialog->update();
        qDebug()<<dir.absolutePath();
    }
}

Could you say me what mistake I am doing? How can get the absolute path of the directory in which the filedialog is currently in?

Was it helpful?

Solution

The QFileDialog has several static methods that do return the selected file and the current directory getExistingDirectory, getOpenFileName, getOpenFileNames, getSaveFileName. You might want to use one of these static functions. The other option is to subclass QFileDialog and override the exec method to return the current directory. http://qt-project.org/doc/qt-4.8/qfiledialog.html

OTHER TIPS

You can replace it with static methods like others suggesting, but I think first you should fix memory leak!

Note that it you code you are creating a NEW QFileDialog that is why you get same directory every time. You use this dialog only once and it is deleted when with this object (probably main window).

So either use static version or create a field in you main window class and create only one dialog and reuse it when needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top