1

I want to include a "remove" icon on entries in my QComboBox, but I am having trouble catching the mouse press event. I've tried to catch it on the combobox, and I've tried reimplemting the QIcon class to catch the mousepress there. No dice. Does anybody know how to do this?

-D

Dutt
  • 13
  • 3
  • Where do you wanna have the icon? Always besides the text, then have a look at: http://doc.trolltech.com/4.6/qcombobox.html#addItem-2 or only when you are moving the mouse over the item? – Mathias Soeken Mar 05 '10 at 19:45
  • How many users expect the item to be removed when you click on the icon in a combobox? I would create a separate delete button besides the combobox, and first let the user select the item he/she wants to remove. – Ton van den Heuvel Mar 06 '10 at 19:57
  • For Rupert - I have no problem getting the icon in there. I want to receive mouse events when a user clicks it. – Dutt Mar 08 '10 at 14:09
  • For Ton - that is a good option. However, I would still like to know if I can receive the mouse events. – Dutt Mar 08 '10 at 14:10

2 Answers2

0

Maybe you can reimplement QComboBox::mousePressEvent(QMouseEvent *e) and use e.x() together with QComboBox::iconSize() to find if the event occurred over the icon.

This will off cause break if a Qt style decides to switch label and icon position in combo boxes. Don't know if that is possible?

Mathias
  • 1,446
  • 2
  • 16
  • 31
  • But I have to agree with the comment to an earlier answer. I dont think this is a good solution for deleting things from a combo box. Generally if something is hard to do, it is because it is not common to do. Hence the solution will be inconsistent compared to other software. The end result is often an alien and/or clumsy UI and the users become confused and/or unhappy. – Mathias Apr 09 '10 at 20:12
0

I've written code a bit like this, where I wanted to put a tree view inside a combo box and I needed to take an action when the check box on the tree was clicked. What I ended up doing was installing an event filter on the combo box to intercept mouse clicks, figure out where the mouse click was happening, and then take an action. Probably you can do the same kind of thing with your icon. Here is the code:

bool TreeComboBox::eventFilter(QObject* object, QEvent* event)
{
  if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease)
  {
    QMouseEvent* m = static_cast<QMouseEvent*>(event); 
    QModelIndex index = view()->indexAt(m->pos());
    QRect vrect = view()->visualRect(index);

    if(event->type() == QEvent::MouseButtonPress  && 
      (model()->flags(index) & Qt::ItemIsUserCheckable) &&
      vrect.contains(m->pos()))
    {
// Your action here
      ToggleItem(index);
      UpdateSelectionString(); 
    }
    if (view()->rect().contains(m->pos()))
      skipNextHide = true;
  }
  return QComboBox::eventFilter(object, event);
}
Corwin Joy
  • 645
  • 7
  • 14