【问题标题】:How to select an item in a QComboBox using the Tab key?如何使用 Tab 键选择 QComboBox 中的项目?
【发布时间】:2018-06-27 22:19:18
【问题描述】:

我有一个闪亮的QComboBox,有三 (3) 个项目可供选择。下面是创建 ComboBox 的代码:

class TabComboBox(QComboBox):

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

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

这是组合框的屏幕截图

除了使用Enter 键之外,我还想使用Tab 键确认我的选择。所以当我使用箭头键或 将鼠标指向Cat 并按Tab,ComboBox 应显示Cat。但是当我按下Tab 时没有任何反应 钥匙。只有Enter 键使我能够选择一个项目。我也想使用Tab 键。我该怎么做?

任何帮助将不胜感激:)

【问题讨论】:

  • 用 Qt 捕获关键事件 .. 检查是否按下了 TAB 键然后编写逻辑。您还需要绕过在组合框外按下的 TAB,因此请检查组合框是否已聚焦
  • 感谢您的回复@MohammadKanan

标签: python pyqt pyqt4 pyqt5 qcombobox


【解决方案1】:

一个可能的解决方案是在TAB键被按下时过滤QEvent::ShortcutOverride事件,并执行改变索引和隐藏弹窗的逻辑。

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_())

【讨论】:

  • 你成功了。感谢您的详细回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2012-03-29
  • 1970-01-01
  • 2015-02-17
  • 1970-01-01
  • 2011-11-07
相关资源
最近更新 更多