从ui中删除QComboBox中的项目

Pet*_*ter 4 qt pyqt qcombobox

我试图以一种用户可以从下拉列表中删除项目的方式调整QComboBox的ui(不先选择它们).

背景是我正在使用QComboBox来指示现在打开哪个数据文件.我也将它用作最近打开的文件的缓存.我希望用户能够删除他不想再列出的条目.这可以是通过点击删除键,或上下文菜单,或任何直接实现的内容.我不想依赖于首先选择项目.在Firefox中可以找到类似的行为,其中可以删除对条目字段的旧缓存建议.

我正在考虑继承QComboBox使用的列表视图,但是,我找不到足够的文档来启动我.

我会很感激任何提示和建议.我正在使用PyQt,但对C++示例没有任何问题.

nwp*_*nwp 5

我使用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);
Run Code Online (Sandbox Code Playgroud)