Search code examples
pythonpyqt5qfiledialog

How do I know which button is clicked in the popup window when using QFileDialog.getSaveFileName


I am using QFileDialog module, and I encounter a problem: how do I know which button is clicked (save or cancel) in the popup window when using QFileDialog.getSaveFileName in PyQt5:

enter image description here


Solution

  • The QFileDialog::getSaveFileName() method returns an empty string if the file was not chosen, that is, when the cancel button is pressed, and instead a non-empty string when the save button is pressed:

    filename, _ = QFileDialog.getSaveFileName()
    if filename:
        print("The save button is pressed")
    else:
        print("The cancel button is pressed")