QIcon inside combobox

一世执手 提交于 2019-12-11 10:09:10

问题


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


回答1:


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);
}



回答2:


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?



来源:https://stackoverflow.com/questions/2389013/qicon-inside-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!