How to ignore the Mouse Wheel Event when Combo box is not in Focus ?



  • Hi.. I have a QComboBox and few QLineEdits, in that currently my Focus is in any of the QLineEdit and i can enter some values in it.. At that time, my Mouse Pointer is in the QComboBox (QComboBox hover state).. Suppose if i scroll my mouse the focus is changing to the QComboBox and the MouseWheel event is taking place.... How can i ignore the Mouse wheel Event when the Combo Box has no focus in it.... ie) The Mouse Wheel Event should be allowed only when the combo Box is clicked and when it has focus.... Plz post your suggestions.....

    Thanks & Regards...


  • Moderators

    This will prevent combo from getting focus on mouse wheel event:

    comboBox->setFocusPolicy( Qt::StrongFocus );
    

    Then you either install an event filter on the combo and filter out wheel event when it has no focus or subclass the QcomboBox class, reimplement wheelEvent(...) and call the original QComboBox::wheelEvent only when it has focus.



  • [quote author="Krzysztof Kawa" date="1362946014"]This will prevent combo from getting focus on mouse wheel event:

    @comboBox->setFocusPolicy( Qt::StrongFocus );@
    [/quote]

    Hi... I tried in this way.. But it doesn't prevent the comboBox from getting focus on mouseWheelEvent...


  • Moderators

    It may not seem it does, but it does. Check the hasFocus() function inside the wheel event with and without it ;) But it's not enough to do what you want.

    Anyway here are both solutions I proposed previously. I checked and they both work fine:

    //custom combo behavior
    class CustomCombo :public QComboBox {
    public:
        explicit CustomCombo(QWidget* parent = 0) : QComboBox(parent) {}
    
        void wheelEvent(QWheelEvent *e)
        {
            if(hasFocus())
                QComboBox::wheelEvent(e);
        }
    };
    
    //and later on in your code
    CustomCombo* combo = new CustomCombo(this);
    combo->setFocusPolicy( Qt::StrongFocus );
    combo->addItems(QStringList() << "1" << "2" << "3" << "4");
    

    or

    //SomeObject can be any QObject, e.g your main window
    bool SomeObject::eventFilter(QObject *obj, QEvent *e)
    {
        if(e->type() == QEvent::Wheel)
        {
            QComboBox* combo = qobject_cast<QComboBox*>(obj);
            if(combo && !combo->hasFocus())
                return true;
        }
    
        return false;
    }
    
    //and then
    QComboBox* combo = new QComboBox(this);
    combo->setFocusPolicy( Qt::StrongFocus );
    combo->installEventFilter( someObjectInstance );
    combo->addItems(QStringList() << "1" << "2" << "3" << "4");
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.