Search code examples
pythonpyqtpyqt5qfiledialog

How does one make QFileDialog.AnyFile work?


Per the PyQt5 docs, specifying QFileDialog.AnyFile should eliminate the requirement that the specified file already exist. But, this doesn't appear to work. Am I doing something wrong, or is this a feature that no longer works? Here's my code:

import os

from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import QApplication, QFileDialog, QWidget


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = "QFileDialog.AnyFile doesn't work."
        self.left = 10
        self.top = 30
        self.width = 320
        self.height = 200

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        dlg= QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        fname, _= dlg.getOpenFileName(parent=self, directory=os.getcwd(),
          caption='Select a file')
        self.show()


if __name__ == '__main__':
   import sys

   app = QApplication(sys.argv)
   ex = App()

   sys.exit(app.exec_())

Solution

  • You have the following misconceptions:

    • QFileDialog::getOpenFileName() is a static method that does not use the "dlg" object but creates a new QFileDialog so setting or modifying any "dlg" property will not influence the QFileDialog that will be displayed.

    • The function QFileDialog::getOpenFileName() aims to obtain the name of an existing file as indicated in the docs, sso the fileMode it has set is QFileDialog::ExistingFile, so modifying that behavior is contradictory.

    This is a convenience static function that returns an existing file selected by the user. If the user presses Cancel, it returns a null string.

    (emphasis mine)


    So if you want to get the name of a file even if it does not exist then you must use the static method QFileDialog::getSaveFileName() as indicated in the docs:

    This is a convenience static function that will return a file name selected by the user. The file does not have to exist.

    (emphasis mine)

    fname, _ = QFileDialog.getSaveFileName(
        parent=self, directory=os.getcwd(), caption="Select a file"
    )