Search code examples
pythonpyqtqfiledialog

PyQt5 - Clicking Cancel on QFileDialog Closes Application


I've noticed that, using the following code, if you choose to click "Cancel" on the FileDialog for "Import File", the entire application closes instead of returning to the menu and awaiting a different choice. How can I get it to just return to the mainMenu?

(Note: I've noticed if I don't put anything after the initial file dialog call, it functions fine.)

Code:

import sys
import xml.etree.ElementTree as et
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


class MainMenu(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        layout = QGridLayout()

        # Create Objects for Main Menu
        logoLabel = QLabel("TESTAPP")
        logoFont = QFont("Broadway", 48)
        logoLabel.setFont(logoFont)
        versionLabel = QLabel("Version 0.1a")
        copyrightLabel = QLabel("Copyright 2016")
        importButton = QPushButton("Import File")
        quitButton = QPushButton("Quit")

        # Set Locations of Widgets
        layout.addWidget(logoLabel, 0, 0)
        layout.addWidget(versionLabel, 1, 0)
        layout.addWidget(copyrightLabel, 2, 0)
        layout.addWidget(importButton, 4, 0)
        layout.addWidget(quitButton, 5, 0)
        self.setLayout(layout)
        self.setWindowTitle("NESSQL")

        # Connect Buttons to Actions
        importButton.clicked.connect(self.importFile)
        quitButton.clicked.connect(self.close)

    def importFile(self):
        # Open dialog box to get the filename
        file = QFileDialog.getOpenFileName(self, caption="File to Import", directory=".",
                                           filter="All Files (*.*)")
        data = et.parse(file)
        root = data.getroot()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainMenu = MainMenu()
    mainMenu.show()
    app.exec_()

Solution

  • by keeping condition for checking whether file is empty or not you can avoid this issue. It goes something like this in your case.

    def importFile(self):
        # Open dialog box to get the filename
        file = QFileDialog.getOpenFileName(self, caption="File to Import", 
                                  directory=".",filter="All Files (*.*)")
    
        if not file[0] == "":
            data = et.parse(file)
            root = data.getroot()