我有一个带有 QComboBox 和取消按钮的 QDialog。用户有两个选项,要么从 QComboBox 中选择一个项目,要么点击取消按钮。 我希望用户可以选择使用键而不是鼠标进行导航。 ESC 将按下取消按钮,上下移动键移动 QComboBox 中的选择,然后输入/返回选择项目。此代码支持 QComboBox 或 QListWidget(取决于 as_list 参数)。最终,我希望这个概念适用于两者。
代码如下:
class OptionsDialog(QDialog):
def __init__(self, title, selected, options, as_list=False, ignore_keys=None):
super().__init__()
self.type = title
self.options = options
self.ignore_keys = ignore_keys
self.combo_box = None
self.list_box = None
self.selected_option = None
self.setModal(True)
top_layout = QVBoxLayout()
layout = QHBoxLayout()
if as_list:
self.list_box = QListWidget()
layout.addWidget(self.list_box)
i = 0
for option in self.options:
self.list_box.insertItem(i, option)
if option == selected:
self.list_box.setCurrentRow(i)
i += 1
self.list_box.setSelectionMode(QListWidget.SingleSelection)
self.list_box.clicked.connect(self.list_box_changed)
else:
self.combo_box = QComboBox()
layout.addWidget(self.combo_box)
for option in self.options:
self.combo_box.addItem(option)
self.combo_box.currentIndexChanged.connect(self.combo_box_changed)
top_layout.addLayout(layout)
layout = QHBoxLayout()
button = QPushButton('Cancel')
layout.addWidget(button)
button.clicked.connect(self.cancel_pressed)
top_layout.addLayout(layout)
self.setLayout(top_layout)
def combo_box_changed(self, index):
self.selected_option = self.combo_box.currentText()
self.close()
def list_box_changed(self):
self.selected_option = self.list_box.currentItem().text()
self.close()
def cancel_pressed(self):
self.selected_option = None
self.close()