5

I would like to add a filter to the following code in order to select only the “CSV files”, but I did not succeed:

def filePath(title):
    qfd = QFileDialog()
    path = "D:\ennine\SIG HTB\BGN"
    f = QFileDialog.getOpenFileName(qfd, title, path)
    return f

2 Answers 2

12

According to the documentation you can add filter in the definition of your class:

QString QFileDialog.getOpenFileName (QWidget parent = None, QString caption = QString(), QString directory = QString(), QString filter = QString(), Options options = 0)

So with your code it should looks like :

def filePath(title):
    qfd = QFileDialog()
    path = "D:\ennine\SIG HTB\BGN"
    filter = "csv(*.csv)"
    f = QFileDialog.getOpenFileName(qfd, title, path, filter)
    return f

You can also add other filter. You need to separate them with a double ;; like so :

"Images (*.png *.xpm .jpg);;Text files (.txt);;XML files (*.xml)"

3
  • Thank you for your prompt response. However, I received the following error: f = QFileDialog.getOpenFileName(qfd, title, path, filter) TypeError: QFileDialog.getOpenFileName(QWidget parent=None, QString caption=QString(), QString directory=QString(), QString filter=QString(), QString selectedFilter=None, QFileDialog.Options options=0): argument 4 has unexpected type 'builtin_function_or_method'
    – ennine
    Oct 29, 2017 at 21:11
  • Many thanks. A small error of typing (The fourth line of the code should be : filter instead of filer)
    – ennine
    Oct 29, 2017 at 21:16
  • Yeah my bad I didn't red carrefully. Glad it helps you help and thank you for upvoting. ;)
    – SIGIS
    Oct 30, 2017 at 7:32
4
dialog = QtGui.QFileDialog()

fname = dialog.getOpenFileName(None, "Window name", "", "CSV files (*.csv)")

Will do the job.

Just pass None as 1st agrument.

Not the answer you're looking for? Browse other questions tagged or ask your own question.