Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove items from QComboBox from ui

Tags:

qt

pyqt

qcombobox

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).

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.

I was considering subclassing the list view used by QComboBox, however, I did not find enough documentation to get me started.

I would be grateful for any hints and suggestions. I am using PyQt, but have no problems with C++ samples.

like image 791
Peter Avatar asked Jul 23 '13 20:07

Peter


People also ask

How do I remove all items from QComboBox?

If you take a look at https://doc.qt.io/qt-5/qcombobox.html you will see the function clear() . Function description: “Clears the combobox, removing all items. Note: If you have set an external model on the combobox this model will still be cleared when calling this function.”

What is a combo box in Qt?

A QComboBox provides a means of presenting a list of options to the user in a way that takes up the minimum amount of screen space. A combobox is a selection widget that displays the current item, and can pop up a list of selectable items. A combobox may be editable, allowing the user to modify each item in the list.


2 Answers

I solved this problem using code from the installEventFilter documentation.

//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);
like image 53
nwp Avatar answered Sep 20 '22 03:09

nwp


comboBox->removeItem(int index) // removes item at index
like image 26
Hesam Qodsi Avatar answered Sep 19 '22 03:09

Hesam Qodsi