Vojislav Stojkovic
Vojislav Stojkovic

Reputation: 8153

Folder browser dialog in Qt

Is there any way to open a folder browser dialog in Qt? When I use QFileDialog with Directory file mode, even if I specify the ShowDirsOnly option, I get the standard file dialog. I would prefer to use a dialog that asks the user to choose a directory from a directory tree.

Here's the PySide code I'm using:

from PySide import QtGui
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
dialog.exec_()

And here's the result I get on Windows 7: File selection dialog

Upvotes: 15

Views: 33899

Answers (4)

ForeverWintr
ForeverWintr

Reputation: 6058

This worked for me:

def getDir(self):
    dialog = QtGui.QFileDialog()
    dialog.setFileMode(QtGui.QFileDialog.Directory)
    dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
    directory = dialog.getExistingDirectory(self, 'Choose Directory', os.path.curdir)

Upvotes: 3

mesut
mesut

Reputation: 2177

Try this line of code, it show you a folder browse dialog:

 ui->txtSaveAddress->setText(folderDlg.getExistingDirectory(0,"Caption",QString(),QFileDialog::ShowDirsOnly));

enter image description here

Upvotes: 3

NG_
NG_

Reputation: 7181

I know, that my answer is some tricky and looks like little hack, but the QFileDialog static methods like getExistingDirectory() use the native dialog, so only limited customization is possible.

However, if you create a QFileDialog instance, you get a dialog that can be customized -- as long as you're happy messing with a live dialog.

For example, this should show a tree view with expandable directories that you can select (hope, it must be not a problem port this code to PySide):

QFileDialog *fd = new QFileDialog;
QTreeView *tree = fd->findChild <QTreeView*>();
tree->setRootIsDecorated(true);
tree->setItemsExpandable(true);
fd->setFileMode(QFileDialog::Directory);
fd->setOption(QFileDialog::ShowDirsOnly);
fd->setViewMode(QFileDialog::Detail);
int result = fd->exec();
QString directory;
if (result)
{
    directory = fd->selectedFiles()[0];
    qDebug()<<directory;
}

Got that method from here

Upvotes: 5

Chris
Chris

Reputation: 17545

It appears that the order in which you call setFileMode() and setOption() matters. Make sure you're calling setFileMode() first:

QFileDialog dialog;
dialog.setFileMode(QFileDialog::Directory);
dialog.setOption(QFileDialog::ShowDirsOnly);
...

Upvotes: 12

Related Questions