Search code examples
pythonpyqt5qfiledialog

PyQt5 enable "select all" (Ctrl/Cmd+A) in file dialogs


For a simple file dialog like:

from PyQt5.Qt import *
import sys

app = QApplication(sys.argv)
OpenFile = QFileDialog()
filenames = OpenFile.getOpenFileNames()
print(filenames)

Shift-select works to select multiple items, but Ctrl/Cmd+A doesn't. Is this an OS thing, or should it be enabled in a certain way in PyQt5?


Edit: The reason why it doesn't work is because of this: https://bugreports.qt.io/browse/QTBUG-17291

Qt expects a menubar with a keyboard shortcut, and a QFileDialog has no menubar, thus lacking shortcuts like "select all".


Solution

  • Based on the bug report in the post above, I found that simply adding a dummy "Select all" command to the menubar on MacOS will make the shortcut available.

    If using .ui files, simply add a Select All to Edit with ⌘A through Qt Creator.

    from PyQt5.QtWidgets import *
    import sys
    
    class Example(QMainWindow):
        def __init__(self):
            super().__init__()
            self.initUI()
            self.initMenuBar()
    
        def initUI(self):
            self.show()
    
        def initMenuBar(self):
            menubar = self.menuBar()
    
            fileMenu = menubar.addMenu("&File")
            editMenu = menubar.addMenu("&Edit")
    
            actionOpen = QAction("Open", self)
            actionOpen.triggered.connect(self.openFiles)
            actionOpen.setShortcut("Ctrl+O")
            fileMenu.addAction(actionOpen)
    
            actionSelectAll = QAction("Select All", self)
            actionSelectAll.setShortcut("Ctrl+A")
            editMenu.addAction(actionSelectAll)
    
        def openFiles(self):
            filenames = QFileDialog.getOpenFileNames()
            print(filenames)
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        ex = Example()
        sys.exit(app.exec_())