从 ui 中删除 QComboBox 中的项目 [英] remove items from QComboBox from ui
问题描述
我正在尝试调整 QComboBox 的 ui,使用户可以从下拉列表中删除项目(无需先选择它们).
I am trying to tweak the ui of a QComboBox in a way that the user can remove items from the drop down list (without first selecting them).
背景是我正在使用 QComboBox 来指示当前打开的是哪个数据文件.我还将它用作最近打开文件的缓存.我希望用户能够删除他不想再列出的条目.这可以通过点击删除键、上下文菜单或任何易于实现的方式来实现.我不想依赖于先选择项目.在 Firefox 中可以找到类似的行为,其中可以删除条目字段的旧缓存建议.
The background is that I am using the QComboBox to indicate which data file is open right now. I am also using it as a cache for recently opened files. I would like the user to be able to remove entries he does not want to have listed anymore. This could be either by just hitting the delete key, or a context menu, or whatever is straightforward to implement. I do not want to rely on selecting the item first. A similar behavior can be found in Firefox, where old cached suggestions for an entry filed can be deleted.
我正在考虑对 QComboBox 使用的列表视图进行子类化,但是,我没有找到足够的文档来帮助我入门.
I was considering subclassing the list view used by QComboBox, however, I did not find enough documentation to get me started.
如果您有任何提示和建议,我将不胜感激.我正在使用 PyQt,但使用 C++ 示例没有问题.
I would be grateful for any hints and suggestions. I am using PyQt, but have no problems with C++ samples.
推荐答案
我使用 installEventFilter 文档.
//must be in a header, otherwise moc gets confused with missing vtable
class DeleteHighlightedItemWhenShiftDelPressedEventFilter : public QObject
{
Q_OBJECT
protected:
bool eventFilter(QObject *obj, QEvent *event);
};
bool DeleteHighlightedItemWhenShiftDelPressedEventFilter::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key::Key_Delete && keyEvent->modifiers() == Qt::ShiftModifier)
{
auto combobox = dynamic_cast<QComboBox *>(obj);
if (combobox){
combobox->removeItem(combobox->currentIndex());
return true;
}
}
}
// standard event processing
return QObject::eventFilter(obj, event);
}
myQComboBox->installEventFilter(new DeleteHighlightedItemWhenShiftDelPressedEventFilter);
这篇关于从 ui 中删除 QComboBox 中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!