PDA

View Full Version : Restrict QFileDialog to one specific directory



spikey
17th February 2010, 20:23
Hi,
how can I restrict the Qt file dialog to only show the files in the given directory (/usr/app/images) and that navigating out of that directory is not possible? (I do not want the user to see any directory navigation possibilities)


const QString IMAGE_DIR="/usr/app/images";
...
QString fileName = QFileDialog::getOpenFileName(
this,
trUtf8("Choose a Picture"),
IMAGE_DIR,
trUtf8("Cool Picture (*.png)")
);

Thank you for a hint.

Spikey

pitonyak
18th February 2010, 03:10
Disclaimer: I have never used the QFileDialog, but, based on what I see, I would try connecting the directory entered signal (see http://doc.qt.nokia.com/4.6/qfiledialog.html#directoryEntered) to my own slot. It is possible that the other signals (such as currentChanged ) may be useful, like when they try to choose a new directory, just a wild guess.

Initially, I would print qDebug statements to learn the behavior, but, if my guess is correct, if the directory you are entering is not the one that you desire, then, set the directory back. The last portion may be a bit tricky, but, take a look and see if it might work.

aerik
12th July 2011, 16:26
It's been a while since this thread was active, but I was having the same problem as spikey, and I stumbled on it from Google.

pitonyak, your idea absolutely worked. Hook a slot up to the directoryEntered signal, and then check whether the new directory startsWith whatever path you want to restrict them to. If so, update an sCurrentDir variable. If not, setDirectory to sCurrentDir.

One important caveat: You also have to check the final file the user chooses, to make sure it's where you expect. Otherwise, the user can type something like "../../restrictedDir/restrictedFile.txt", and the dialog will even give them a drop-down of file completion to help them! Be aware that users can still see files outside your restricted directory area, too, so if viewing files outside is a concern, this might not be a complete solution for you.

Also, when you check the final file, make sure you do it with a "/" at the end of your path. Otherwise, instead of something like "/acceptableDir/acceptableFile.txt", the user could manually type in a file like "../acceptableDirWhoopsNoItsNot/restrictedFile.txt".