Search code examples
pythonpyqtpyqt4pyqt5qcombobox

How to select an item in a QComboBox using the Tab key?


I have a shiny QComboBox that has three (3) items to select. Here's the code to create the ComboBox:

class TabComboBox(QComboBox):

    def __init__(self, parent=None):
        super().__init__(parent)

        # Populate combobox
        self.addItems(['Dog', 'Cat', 'Bird'])

Here's the screenshot of the ComboBox

I want to confirm my selection using the Tab key aside from using the Enter key. So when I use the arrow keys or point my mouse in Cat and press Tab, the ComboBox should display Cat. But nothing happens when I pressed the Tab key. Only the Enter key enables me to select an item. I also want to use the Tab key. How can I do that?

Any help will be appreciated :)


Solution

  • A possible solution is to filter the QEvent::ShortcutOverride event when the TAB key is pressed, and perform the logic of changing the index and hiding the popup.

    class TabComboBox(QComboBox):
        def __init__(self, *args, **kwargs):
            QComboBox.__init__(self, *args, **kwargs)
            # Populate combobox
            self.addItems(['Dog', 'Cat', 'Bird'])
            self.view().installEventFilter(self)
    
        def eventFilter(self, obj, event):
            if event.type() == QEvent.ShortcutOverride:
                if event.key() == Qt.Key_Tab:
                    self.hidePopup()
                    self.setCurrentIndex(self.view().currentIndex().row())
                    return True
            return QComboBox.eventFilter(self, obj, event)
    
    
    if __name__ == "__main__":
        app =QApplication(sys.argv)
        myapp = QWidget()
        myapp.setLayout(QVBoxLayout())
        myapp.layout().addWidget(TabComboBox())
        myapp.layout().addWidget(QTextEdit())
        myapp.show()
        sys.exit(app.exec_())