Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when "Cancel" while opening a file in PyQt4

Tags:

python

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?

like image 539
Krin123 Avatar asked Feb 18 '15 21:02

Krin123


2 Answers

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)
like image 154
Luke Woodward Avatar answered Nov 14 '22 22:11

Luke Woodward


as one above said, you should debug and check what kind of answer "openFilename" returns.

in Pyqt5, when you press cancel or 'x' to close the window, it returns a tuple

so to get around the issue:

openFileName = QFileDialog.getOpenFileName(self)
if openFileName != ('', ''):
    with open(openFileName [0], 'r') as f:
        file_text = f.read()
        self.text.setText(file_text)
like image 26
Danny Kaminski Avatar answered Nov 14 '22 22:11

Danny Kaminski