如何使用 Tab 键 select QComboBox 中的一个项目?
How to select an item in a QComboBox using the Tab key?
我有一个闪亮的 QComboBox
,其中有三 (3) 个项目 select。下面是创建 ComboBox 的代码:
class TabComboBox(QComboBox):
def __init__(self, parent=None):
super().__init__(parent)
# Populate combobox
self.addItems(['Dog', 'Cat', 'Bird'])
这是 ComboBox 的屏幕截图
除了使用 Enter
键外,我还想使用 Tab
键确认我的 selection。所以当我使用箭头键或
将鼠标指向 Cat 并按 Tab
,ComboBox 应显示 Cat。但是当我按下 Tab
时没有任何反应
钥匙。只有 Enter
键可以让我 select 一个项目。我也想使用 Tab
键。我该怎么做?
任何帮助将不胜感激:)
一种可能的解决方案是在按下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_())
我有一个闪亮的 QComboBox
,其中有三 (3) 个项目 select。下面是创建 ComboBox 的代码:
class TabComboBox(QComboBox):
def __init__(self, parent=None):
super().__init__(parent)
# Populate combobox
self.addItems(['Dog', 'Cat', 'Bird'])
这是 ComboBox 的屏幕截图
除了使用 Enter
键外,我还想使用 Tab
键确认我的 selection。所以当我使用箭头键或
将鼠标指向 Cat 并按 Tab
,ComboBox 应显示 Cat。但是当我按下 Tab
时没有任何反应
钥匙。只有 Enter
键可以让我 select 一个项目。我也想使用 Tab
键。我该怎么做?
任何帮助将不胜感激:)
一种可能的解决方案是在按下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_())