【发布时间】:2012-08-31 05:46:38
【问题描述】:
我正在使用 pyqt 编写一个简单的代码
在代码中,我调用了QFileDialog,但是当我使用静态函数调用它时一切正常,但使用普通方法,即使用dialog.exec_(),,我在文件对话框窗口中看不到任何文件。
只有在输入文件的完整路径后,我才能在文件对话框窗口中看到该文件。
请注意,此问题仅在我调用FileDialoghandler 函数时出现,如果我不这样做,无论我如何调用QFileDialog,一切正常。
而且这个问题只在 Linux 上,在 Windows7 上一切正常。
我想知道这是 PyQt 错误还是我在这里遗漏了什么?
代码如下:
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import *
from PyQt4.QtCore import QAbstractFileEngine
from PyQt4.QtCore import QAbstractFileEngineHandler
from PyQt4.QtCore import QFSFileEngine
class FileDialogHandler(QAbstractFileEngineHandler):
def create(self,filename):
if str(filename).startswith(':'):
return None # Will be handled by Qt as a resource file
print("Create QFSFileEngine for {0}".format(filename))
return QFSFileEngine(filename)
class Example(QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
openFile = QAction(QIcon('open.png'), 'Open', self)
openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Open new File')
openFile.triggered.connect(self.showDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('File dialog')
self.show()
def showDialog(self):
handler = FileDialogHandler()
#using QFileDialog.getOpenFileName works fine
fname = QFileDialog.getOpenFileName(None, 'Open file', '/home','All files (*.*)')
#dialog = QFileDialog()
#dialog.setOption(QFileDialog.DontUseNativeDialog,False)
#if dialog.exec_():
#fname = dialog.selectedFiles()
#else:
#fname = None
f = open(fname, 'r')
with f:
data = f.read()
self.textEdit.setText(data)
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
【问题讨论】:
-
确认它在 Linux 上不适合我。但是,相同的代码确实适用于 PySide - 所以它可能是一个 PyQt 错误。不过,我建议您在PyQt mailing list 上报告它以获得明确的答案。
-
似乎可以在 OS X 上运行。为什么你真的需要
QFSFileEngine? -
小心你的
f=open(fname,'r'); with f。您不仅可以将这两个语句放在一个with open(fname, 'r') as f中,而且首先应该将其封装在try... except IOError中,这样如果用户按下“取消”(即,当fname=""时),您就不会崩溃/跨度> -
它在 Win7 上对我不起作用。并与 PySide 一起使用。
-
@ekkhumoro:感谢您的确认,我正在迁移到 PySide
标签: python pyqt qfiledialog