Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pyqt

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?

like image 519
Eljee Avatar asked Jul 14 '14 14:07

Eljee


2 Answers

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
)
like image 73
Andy Avatar answered Oct 11 '22 21:10

Andy


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
    )
like image 31
Arg0s Avatar answered Oct 11 '22 21:10

Arg0s