6

I am writing a simple code using pyqt

In the code, I invoke a QFileDialog, however when I invoke it using the static functions all works fine, but with the normal method i.e. using dialog.exec_(), I do not see any files in the file dialog window.

Only after typing the complete path of the file can I see the file in the file dialog window. Note that this issue is only when I invoke the FileDialoghandler function, If I don't do that, no matter how I invoke the QFileDialog, everything works fine. And also this issue is only on Linux, on Windows7 everything works ok. I am wondering whether this is a PyQt bug or am I missing something here?

Code is as follows:

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()
user1637766
  • 61
  • 1
  • 4
  • Confirmed that it doesn't work for me on Linux. However, the same code does work with PySide - so it possibly it is a PyQt bug. I would suggest you report it on the [PyQt mailing list](http://www.riverbankcomputing.com/mailman/listinfo/pyqt) to get a definitive answer, though. – ekhumoro Aug 31 '12 at 16:42
  • Seems to work on OS X. Why do you really need a `QFSFileEngine`? – Pierre GM Aug 31 '12 at 16:53
  • Be careful with your `f=open(fname,'r'); with f`. Not only could you put the two statements in a single `with open(fname, 'r') as f`, but you should above all encapsulate it in a `try... except IOError` so that you don't crash if the user presses 'Cancel' (ie, when `fname=""`) – Pierre GM Aug 31 '12 at 16:54
  • It doesn't work for me on Win7. And works with PySide. – Avaris Sep 01 '12 at 01:37
  • @ekkhumoro: Thanks for confirming that, I am migrating to PySide – user1637766 Sep 01 '12 at 18:25
  • @PierreGM: Yes all of that is taken care in the actual code(this is just a sample app I was making to make sure the issue wasnt because of our software)..and yea, I needed the QFSFileEngine because in my actual code theres a custom file engine that Qt uses, and it causes thread safety related issues, so I wanna use Qt's default file engine..Also, if we dont create an instance of the FileDialogHandler class, QFileDialog works perfectly ok(but ofcourse some other thread safety issues from our software pop up) – user1637766 Sep 01 '12 at 18:31
  • @user1637766, Qt4 is no longer being actively developed or maintained. You might consider migrating to Qt5 or even Qt6. – bfris Jan 14 '22 at 18:59

2 Answers2

11

I encountered a similar problem not long ago with the getOpenFilename. For me the solution was to change the backend from native to Qt's own implementation of the dialog. This can be achieved withan extended calling syntax which looks like:

filename = QtGui.QFileDialog.getOpenFileName(self,
                                             'Open file',
                                             '/home',
                                             'All files (*.*)',
                                             options=QtGui.QFileDialog.DontUseNativeDialog)

After I changed to this calling syntax I never had any problems again.

wagnerpeer
  • 937
  • 7
  • 22
  • 1
    Wow, you have just answered my question over here https://stackoverflow.com/questions/58122168/in-pyqt5-getopenfilename-does-not-result-in-a-file-selection-pop-up I will link this question over there so more people know of this – zwep Sep 26 '19 at 19:59
0

Encountered the same problem in Windows 10 running the code from command prompt without any IDE. Including options=QtGui.QFileDialog.DontUseNativeDialog did solve the problem. (with python 3.10). For Example:

self.path_open, _ = QFileDialog.getOpenFileName(self, "Open file", "", "e-documents (*.docx *.pdf)",
                                                options=QFileDialog.DontUseNativeDialog)
joanis
  • 10,635
  • 14
  • 30
  • 40
Paraclete
  • 291
  • 3
  • 4