Question

I have the need to get one or more directories from the user, and I'm trying to use QFileDialog for this, as shown below. (using QT 5.2)

The problem is that if the user surfs down a directory from their starting directory, then when they select their directories, in addition to those selected directories the dialog returns the parent directory. This only happens for the immediate parent. If they surf down two directories, they still only get the one extra parent entry. If their last navigation was to go back up to the previous directory, they get no extra parent entry.

My question here is: a) Is this a known bug with the QFileDialog? and b) Is there a fix/workaround?

The best I can think up is to write code to compare the first selected entry against the second, and chuck it if it is the parent directory.

QStringList open_directories (const std::string & start_dir) {
    QFileDialog dialog (0, "Import Load Directories", from_string(start_dir), QString());
    dialog.setFileMode(QFileDialog::DirectoryOnly);
    dialog.setOption(QFileDialog::DontUseNativeDialog,true);
    QListView *list = dialog.findChild<QListView*>("listView");
    if (list) {
     list->setSelectionMode(QAbstractItemView::MultiSelection);
    }

    QTreeView *tree = dialog.findChild<QTreeView*>();
    if (tree) {
        tree->setSelectionMode(QAbstractItemView::MultiSelection);
    }
    QStringList file_names;
    if (dialog.exec()) {
        file_names = dialog.selectedFiles();
    }
    return file_names;
}
Was it helpful?

Solution

The problem, how I see it, is in using specific selection mode for file dialog item views, when new selection does not deselect the previous selection. So, when you navigate through the hierarchy down you click on directory nodes before making the final selection. Thus you accumulate additional items. What I propose, is using QAbstractItemView::ContiguousSelection mode, that deselects the old selection. So, your code should look like:

[..]
if (list) {
    list->setSelectionMode(QAbstractItemView::ContiguousSelection);
}

QTreeView *tree = dialog.findChild<QTreeView*>();
if (tree) {
    tree->setSelectionMode(QAbstractItemView::ContiguousSelection);
}
[..]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top