Igor Igor - 2 years ago 261
Python Question

Python PyQt Pyside - setNameFilters in QFileDialog does not work

(Windows 7 64 Bit, PyCharm 3.4.1 Pro, Python 3.4.0, PySide 1.2.2)

I want to make a file dialog with filters and preselect one filter.

If i use the static method, it works, i can use filters and preselect one filter.

dir = self.sourceDir
filters = "Text files (*.txt);;Images (*.png *.xpm *.jpg)"
selected_filter = "Images (*.png *.xpm *.jpg)"
fileObj = QFileDialog.getOpenFileName(self, " File dialog ", dir, filters, selected_filter)

If i use an object it does not work, my filters are not there.

file_dialog = QFileDialog(self)
file_dialog.setNameFilters("Text files (*.txt);;Images (*.png *.jpg)")
file_dialog.selectNameFilter("Images (*.png *.jpg)")

Why does this not work?

enter image description here
enter image description here

Answer Source

You have misunderstood how QFileDialog works.

The functions getOpenFileName, getSaveFileName, etc are static. They create an internal file-dialog object, and the arguments to the function are used to set properties on it.

But when you use the QFileDialog constructor, it creates an external instance, and so setting properties on it have no effect on the internal file-dialog object created by the static functions.

What you have to do instead, is show the external instance you created:

file_dialog = QFileDialog(self)
# the name filters must be a list
file_dialog.setNameFilters(["Text files (*.txt)", "Images (*.png *.jpg)"])
file_dialog.selectNameFilter("Images (*.png *.jpg)")
# show the dialog

However, doing things this way comes with a big cost, because you cannot get a native file-dialog by using this method - you will always get the built-in Qt file-dialog instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download