Search code examples
pythonpyqt4

Error when "Cancel" while opening a file in PyQt4


I have a simple PyQt4 GUI where I have the user open a txt file that will display in the GUI's QPlainTextEdit widget. Here's the pseudo code:

class mainWindow(QtGui.QWidget):
    def __init__(self):
        super(mainWindow, self).__init__()
        self.layout = QtGui.QVBoxLayout()
        self.plain = QtGui.QPlainTextEdit()
        self.openButton = QtGui.QPushButton("OPEN")
        self.layout.addWidget(self.plain)
        self.layout.addWidget(self.openButton)
        self.openButton.clicked.connect(self.openFile)

    def openFile(self):
        openFileName = QtGui.QFileDialog.getOpenFileName(None, "Open File","/some/dir/","TXT(*.txt);;AllFiles(*.*)")
        openFile = open(openFileName,'r').read()
        self.plainTextEdit.appendPlainText(openFile)

So I click the "OPEN" button and the QFileDialog pops up, but if I hit the "CANCEL" button within the QFileDialog, I get this error:

IOError: [Errno 2] No such file or directory: PyQt4.QtCore.QString(u'')

I know as the programmer that this error can be easily ignored and does not impact the code's operation whatsoever, but the users do not know that. Is there a way to eliminate this error from printing in terminal?


Solution

  • Yes: simply check the return value from getOpenFileName. This method returns an empty QString if the user clicks Cancel. As empty QStrings are considered false, you can check to see if the user chose a file instead of clicking Cancel by putting the last two lines of your openFile method in an if openFileName: statement:

        def openFile(self):
            openFileName = QtGui.QFileDialog.getOpenFileName(None, "Open File","/some/dir/","TXT(*.txt);;AllFiles(*.*)")
            if openFileName:
                openFile = open(openFileName,'r').read()
                self.plainTextEdit.appendPlainText(openFile)