Mouse cursor over QWidget



  • Greeting Qt community,

    I'm looking for a way to maintain a "cursor hovered" property.

    Even when the mouse is pressed or when a window overlaps my QWidget.

    Is there a way to check if the cursor is inside a visible part of my QWidget ?

    Thanks ♥.

    B.A.



  • Hi,

    you can use setMouseTracking() to enable mouse tracking and implement mouseMoveEvent() to check mouse position.
    For example

    @
    void MyWidget::mouseMoveEvent(QMouseEvent *_event)
    {
    if (this->rect().contains(_event->pos())) {
    // Mouse over Widget
    }
    else {
    // Mouse out of Widget
    }
    }
    @



  • There's already a css property for hovered. If you're just using it to change the appearance of the widget you can use that without doing any coding.



  • Another way is to install an event filter and look for the enter and leave events, a trivial example:

    @
    #include <QtGui>
    #include <QtCore>

    class Widget : public QWidget {
    public:
    Widget(QWidget *parent=0) : QWidget(parent) {
    installEventFilter(this);

        QVBoxLayout *l=new QVBoxLayout(this);
        label=new QLabel("(Default)", this);
        l->addWidget(label);
    }
    

    protected:
    bool eventFilter(QObject *object, QEvent *event){
    if(object==this && (event->type()==QEvent::Enter || event->type()==QEvent::Leave))
    label->setText(event->type()==QEvent::Enter ? "Hovering" : "Not Hovering");
    }

    private:
    QLabel *label;
    };

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec&#40;&#41;;
    

    }
    @



  • [quote author="mcosta" date="1365013118"]Hi,

    you can use setMouseTracking() to enable mouse tracking and implement mouseMoveEvent() to check mouse position.
    @[/quote]

    This doesn't work because mouseMoveEvent() isn't called unless the cursor is inside the widget, so your if() condition is always true!

    You can theoretically use grabMouse() but I feel like that is a potentially bad way to do what should be fairly simple.



  • -Here is some better code:- See below
    @
    class MyWidget : public QWidget
    {
    // ...
    protected:
    bool event(QEvent* e) override;
    // ...
    };

    bool MyWidget::event(QEvent* e)
    {
    if (e->type() == QEvent::Enter)
    qDebug() << "Enter"; // Or whatever
    if (e->type()==QEvent::Leave)
    qDebug() << "Leave";

    return QWidget::event(e); // Or whatever parent class you have.
    }@

    Actually screw that - there are already leaveEvent() and enterEvent() functions in QWidget!


Log in to reply
 

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