Python PyQt Pyside-QFileDialog中的setNameFilters不起作用 [英] Python PyQt Pyside - setNameFilters in QFileDialog does not work
问题描述
(Windows 7 64位,PyCharm 3.4.1 Pro,Python 3.4.0,PySide 1.2.2)
(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()
为什么这不起作用?
推荐答案
您误解了QFileDialog
的工作方式.
函数getOpenFileName
,getSaveFileName
等是静态.他们创建一个内部文件对话框对象,该函数的参数用于设置其属性.
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.
但是,当您使用QFileDialog
构造函数时,它会创建一个 external 实例,因此对其设置属性不会影响所创建的 internal 文件对话框对象通过静态功能.
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_()
这篇关于Python PyQt Pyside-QFileDialog中的setNameFilters不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!