简体   繁体   English

PyQt5 - 在 QFileDialog 上单击取消关闭应用程序

[英]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.我注意到,使用以下代码,如果您选择在 FileDialog 上单击“取消”以获取“导入文件”,整个应用程序将关闭,而不是返回菜单并等待不同的选择。 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_()

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM