GriMel
GriMel

Reputation: 2320

Native custom file dialog PyQt

In my PyQt app I'm trying to run native but custom QFileDialog.
My code looks like this.

dlg = QtGui.QFileDialog(self, caption=self.tr("Select a file")))
dlg.setNameFilters("Text files (*.txt)")

if dlg.exec_():
    name = dlg.selectedFiles()

but this shows a Qt dialog, not native. I've tried

dlg.setOption(QtGui.QFileDialog.DontUseNativeDialog, False)

but this didn't help.
How do I run custom native QFileDialog?

Upvotes: 1

Views: 2511

Answers (2)

Brendan Abel
Brendan Abel

Reputation: 37559

You can only get the native File Dialogs by using the static functions on QFileDialog. The DontUseNativeDialog option only works when using the static functions.

QFileDialog.getSaveFileName(), etc.

From the Docs

The easiest way to create a QFileDialog is to use the static functions. On Windows, Mac OS X, KDE and GNOME, these static functions will call the native file dialog when possible.

QFileDialog.DontUseNativeDialog   0x00000010  

Don't use the native file dialog. By default, the native file dialog is used unless you use a subclass of QFileDialog that contains the Q_OBJECT macro.

Upvotes: 1

ekhumoro
ekhumoro

Reputation: 120768

A custom native dialog is a contradiction interms. The main reason for choosing to use a native dialog is so that you can get exactly what the platform normally provides.

But this is a moot point, since getOpenFileName allows you to achieve what you want without any customization:

name = QFileDialog.getOpenFileName(
            parent=self,
            caption=self.tr("Select a file"),
            filter=self.tr('Text files (*.txt)'),
            )
if name:
    print(name)

In addition to the above arguments, there's also dir, which allows you to set the start directory; selectedFilter, which allows you to set the initial filter; and options, which allows you to set one or more Option values (not all of which are relevant for native file-dialogs).

Upvotes: 1

Related Questions