Search code examples
pythonpyqt5focusqfiledialogqlistview

PyQt5 QFileDialog - Highlight Suggested File in the QListView Widget


I’m using PyQt5 on a Windows platform. I want to present a QFileDialog to the user with the suggested file highlighted in both the QListView and the QLineEdit widgets within the QFileDialog window. The selectFile() method adds the filename to the QLineEdit widget and highlightss it, but does not highlight the file in the QListView widget.

I tried the suggestion in How to setFocus() on QListView in QFileDialog in PyQt5?, but I could not see that the QListView had focus and could not highlight a file with selectFile().

In QFileDialog, is there a way to highlight the filename in the QistView and in the QLineEdit widgets? If not, is there a way to highlight the filename in just the QListView?

Here is a minimalized script that shows the filename highlighted in the QLineEdit widget.

import sys
from PyQt5.QtWidgets import QApplication, QFileDialog
from PyQt5.QtCore import QDir

class MyClass(QFileDialog):
    def __init__(self):
        super().__init__()
        self.DontUseNativeDialog
        self.openFile()

    def openFile(self):
        qdir = QDir()
        qdir.setPath('C:\\Users\\Slalo\\Documents\\VideoGates\\PVRTop\\Folder') 
        qdir.setSorting(QDir.Name | QDir.Reversed)
        qdirlist = qdir.entryList()
        self.setWindowTitle('Open File')
        self.setDirectory(qdir)
        self.setNameFilter('All(*.*)') 
        self.selectFile(qdirlist[1])        
        
        if self.exec():
            fname = self.selectedFiles()
            print(fname)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    dlg = MyClass()
    sys.exit(app.exec())

Solution

  • After testing @musicamante 's patience, here is the solution. The QFileDialog window looks a little different than the native Windows dialog, but that's OK - it works as intended. Here is the corrected script.

    import sys, os
    from PyQt5.QtWidgets import QApplication, QFileDialog
    
    class MyClass(QFileDialog):
        def __init__(self):
            super().__init__()
            self.setOption(QFileDialog.DontUseNativeDialog)
            self.openFile()
    
        def openFile(self):
            dirname = 'C:\\Users\\Slalo\\Documents\\VideoGates\\PVRTop\\Folder'
            fileList = os.listdir(dirname)
            self.setWindowTitle('Open File')
            self.setDirectory(dirname)
            self.setNameFilter('All(*.*)') 
            self.selectFile(fileList[1]) 
            
            if self.exec():
                fname = self.selectedFiles()
                print(fname)
            
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        dlg = MyClass()
        sys.exit(app.exec())