在PyQt4中打开文件时“取消”时出错

时间:2015-02-18 21:56:20

标签: python pyqt4

我有一个简单的PyQt4 GUI,我让用户打开一个txt文件,该文件将显示在GUI的QPlainTextEdit小部件中。 这是伪代码:

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)

所以我点击“OPEN”按钮弹出QFileDialog,但如果我点击QFileDialog中的“CANCEL”按钮,我会收到此错误:

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

我知道程序员可以轻易忽略此错误,并且不会影响代码的操作,但用户不知道这一点。有没有办法在终端中打印消除这个错误?

2 个答案:

答案 0 :(得分:6)

是:只需检查getOpenFileName的返回值即可。如果用户单击“取消”,则此方法返回空QString。由于空QString被视为false,您可以通过将openFile方法的最后两行放在if openFileName:语句中来检查用户是否选择了文件而不是单击取消:

    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)

答案 1 :(得分:0)

如上所述,您应该调试并检查“ openFilename”返回的答案是什么。

在Pyqt5中,当您按“取消”或“ x”关闭窗口时,它将返回一个元组

所以要解决这个问题:

openFileName = QFileDialog.getOpenFileName(self)
if openFileName != ('', ''):
    with open(openFileName [0], 'r') as f:
        file_text = f.read()
        self.text.setText(file_text)