10

According to getOpenFileName instructions:

QString fileName = QFileDialog.getOpenFileName(this, tr("Open File"), 
                                          "/home",
                                          tr("Images (*.png *.xpm *.jpg)"));

How can I make the dialog remember the path the last time when I close it?

and what does the tr mean in the tr("Open File")?

Thanks

eyllanesc
  • 190,383
  • 15
  • 87
  • 142
Liao Zhuodi
  • 2,366
  • 4
  • 22
  • 39

1 Answers1

19

If you omit the dir argument (or pass in an empty string), the dialog should remember the last directory:

filename = QtGui.QFileDialog.getOpenFileName(
               parent, 'Open File', '', 'Images (*.png *.xpm *.jpg)')

The tr function is used for translating user-visible strings. You can omit it if you won't ever be providing translations for your application.

EDIT:

It seems that the start directory may not be automatically remembered on all platforms/desktops, depending on whether you use the native dialog or not. If Qt's built-in dialog is used, the start directory should always be automatically remebered on all platforms (even between invokations of the application). To try the non-native dialog, do:

filename = QtGui.QFileDialog.getOpenFileName(
               parent, 'Open File', '', 'Images (*.png *.xpm *.jpg)',
               None, QtGui.QFileDialog.DontUseNativeDialog)

Alternatively, you can use the QFileDialog constructor, which will always create a non-native dialog:

dialog = QtGui.QFileDialog(parent)
dialog.setWindowTitle('Open File')
dialog.setNameFilter('Images (*.png *.xpm *.jpg)')
dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
if dialog.exec_() == QtGui.QDialog.Accepted:
    filename = dialog.selectedFiles()[0]
eyllanesc
  • 190,383
  • 15
  • 87
  • 142
ekhumoro
  • 98,079
  • 17
  • 183
  • 279
  • Thanks for you reply, but it doesn't work. It gives me this: TypeError: argument 3 of QFileDialog.getOpenFileName() has an invalid type. I am using PyQt4, forget to say. – Liao Zhuodi Apr 11 '14 at 12:44
  • @liaozd. Sorry, `None` will only work with Python3 - use an empty string instead (works with both Python2 and Python3). – ekhumoro Apr 11 '14 at 17:18
  • yes I am using python2.7 and PyQt4 in my CentOS6.4, but the empty string way seems do not work for me, it always open the python script folder as the default position. – Liao Zhuodi Apr 12 '14 at 02:00
  • @liaozd. What desktop do you use? It's possible that my original solution won't work on all platforms/desktops - see my updated answer for other options. – ekhumoro Apr 12 '14 at 03:25
  • I am using the Linux CentOS 6.4, thanks for your help. this part works "None, QtGui.QFileDialog.DontUseNativeDialog)". – Liao Zhuodi Apr 13 '14 at 13:57