Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)")
file_dialog.getOpenFileName() 

Why does this not work?

enter image description hereenter image description here

like image 388
Igor Avatar asked Dec 05 '22 04:12

Igor


1 Answers

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
file_dialog.exec_()
like image 53
ekhumoro Avatar answered Dec 06 '22 19:12

ekhumoro