PyQt: QFileDialog.getExistingDirectory using a default directory, user independant

pyqt, python

Solution

You can get the user's home directory by using os.path.expanduser

>>> from os.path import expanduser
>>> expanduser("~")
/home/user_name

This works on Windows and Linux.

Your code block will look like this then

my_dir = QtGui.QFileDialog.getExistingDirectory(
    self,
    "Open a folder",
    expanduser("~"),
    QtGui.QFileDialog.ShowDirsOnly
)

Problem

When using the `QFileDialog.getExistingDirectory` I've found the way to specify the default path to a directory. I wanted to use a default directory somewhere in my (user) home folder on my Linux (Mint) machine. I used: ``` my_dir = QtGui.QFileDialog.getExistingDirectory( self, "Open a folder", "/home/my_user_name/", QtGui.QFileDialog.ShowDirsOnly ) ``` Which worked beautifully. The next 'level' is now to be able to do this for every user. I tried the standard Linux way and change `/home/my_user_name/` to `~/`. That did not work. It resulted in the working directory instead of the user's dir. Should I use more system arguments when calling my app from the terminal? Or am I missing a PyQt function?

Original source