pythonsortingpyqt5qfiledialoggetopenfilename

PyQt5: keep selection order with QFileDialog.getOpenFileNames


I am writing a GUI where the user is asked to select multiple files to open. For this purpose I use QFileDialog. I need to keep track of the order in which the user selected the files, is it possible?

I have the following:

filepath, _ = QFileDialog.getOpenFileNames(self, "Open File", "", "CSV Files(*.csv);;All Files (*)")

but the filepath contains the paths of the files, ordered as I found them in the folder, and not depending on the selction order. I know that I can ask the user to select a single file at a time, but with many files to open, it becomes cumbersome for the user.


Solution

  • By default, the static QFileDialog functions will show a native file-dialog. It seems that on your system, the native file-dialog automatically sorts the selected files (which may not be the case on all platforms). However, Qt's built-in file-dialog doesn't have this behaviour, so a simple fix would be to use that instead:

    filepaths, _ = QFileDialog.getOpenFileNames(
        self, "Open File", "", "CSV Files(*.csv);;All Files (*)",
        options=QFileDialog.DontUseNativeDialog)
    print('\n'.join(filepaths))
    

    Example output:

    /home/foo/tmp/mbe-issue.csv
    /home/foo/tmp/data.csv
    /home/foo/tmp/test.csv
    /home/foo/tmp/category_list.csv
    /home/foo/tmp/data2.csv
    

    This behaviour isn't explicitly documented, but it works for me using both Qt-5.15.6 and Qt-6.4.0, so it appears to be a stable feature.