[英]Open a pop-up window after selecting files in QFileDialog - Python
[英]No files visible in the QFileDialog window
我正在使用 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()
我不久前用getOpenFilename遇到了類似的問題。 對我來說,解決方案是將后端從本機更改為Qt自己的對話框實現。 這可以通過擴展的調用語法實現,如下所示:
filename = QtGui.QFileDialog.getOpenFileName(self,
'Open file',
'/home',
'All files (*.*)',
options=QtGui.QFileDialog.DontUseNativeDialog)
在我改為這個調用語法后,我再也沒有遇到任何問題。
在沒有任何 IDE 的情況下從命令提示符運行代碼的 Windows 10 中遇到了同樣的問題。 包括 options=QtGui.QFileDialog.DontUseNativeDialog 確實解決了這個問題。 (使用python 3.10)。 例如:
self.path_open, _ = QFileDialog.getOpenFileName(self, "Open file", "", "e-documents (*.docx *.pdf)",options=QFileDialog.DontUseNativeDialog)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.