Question

I'm writing a small Python code to join text files, and the files are selected as an user input. But it's important that I get the order of the users selection, as I want to join the files in the selected order. But I see that the list returned by getOpenFileNames does not preserve the selection order.

Does anybody have any suggestion to capture the selection order?

Thank you.

Was it helpful?

Solution

I originally wanted to suggest writing a callback for the currentChanged signal that tracks the selection, but it seems like this signal doesn't get called when using getOpenFileNames. An alternative would be displaying the dialog with show() and connecting a callback to filesSelected, which is called after the user clicks the "open" button on the dialog. The argument to the callback is a list with the selected files which seems to be in the order of their selection (just tested it on python3/pyqt4).

def callback(files):
    joined_files = ''.join([open(f).read() for f in files])
    do_something_with(joined_files)

dialog = QtGui.QFileDialog()
dialog.setFileMode(3) #allow selection of multiple files
dialog.filesSelected.connect(callback)
dialog.show()

One problem with this is that the order isn't indicated to the user in an easy way - the "file" textbox contains the ordered files' names, but this is messy when you select more than a few files. A better but slightly more complicated approach would be building a widget or dialog with a FileDialog for selecting files and a List/TableWidget holding the files to process, where the user could add Files one at a time. This would allow for a better overwiew as well as easy selection of files from multiple directories and better extendability (e.g. filtering, rearranging, sorting the selection).

OTHER TIPS

self.filename = QtGui.QFileDialog.getOpenFileNames(
    self,
    "Cargar tu documento",
    self.lastOpenedFile,
    "*.doc;*.odt;*.pdf" )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top