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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With