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?
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
)
You can also get home folder for any user by obtaining the environment variable "HOME" through os.getenv(varname)
.
>>> import os
>>> os.getenv("HOME")
'/home/my_user_name'
Your code could look like this:
import os
home = os.getenv("HOME")
my_dir = QtGui.QFileDialog.getExistingDirectory(
self,
"Open a folder",
home,
QtGui.QFileDialog.ShowDirsOnly
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With