Qt World Summit: Register Today!

QWidget::mouseMoveEvent() with and without button pressed

  • Greetings.

    I'm reimplementing the QWidget::mouseMoveEvent() function for a custom widget. I need that the function can distinguish when the mouse move event is performed without any button pressed and when the mouse movement is performed keeping the left mouse button held down.

    The problem arises because the function QMouseEvent::button() returns Qt::Nobutton for mouse motion events. What can I do in this case?.

    Thanks in advance for any help and/or suggestions.

  • Qt Champions 2017

    enable setMouseTracking on widget. You will receive move events without without any buttons pressed i.e QMouseEvent::button() returns nobutton.

    If the button is pressed and moved, QMouseEvent::button() will give you appropriate buttons inside moveevent.

  • Greetings.

    Probe what you said, but did not work.

    I have within my function MyWidget::mouseMoveEvent() something like as follows:


    if( event->button() == Qt::LeftButton )
    /* Shares corresponding to: mouse has moved and the left button pressed /
    otherwise */

    Am I doing something wrong?.

    According to what I read in the documentation of Qt, the function QMouseEvent::button() always returns Qt::NoButton for mouse motion events (I understand then, which returns Qt::NoButton regardless of whether or not a button down ... or am I wrong?).

    Before starting this post, I had solved the problem by using a logical variable (member of my class), which was initiated in false, is set to true when entering mousePressEvent() and returned to false mouseReleaseEvent(). This worked well, but I guess it must be a way (the right way) more elegant using Qt classes (QMouseEvent here and maybe some other classes)... What is that other way?

  • @isaacEnrique Use event->buttons() instead of event->button().

  • @texas

    Really? :)
    After 7 years?

  • @Pl45m4 Better late than never? lol

  • @texas

    Yeah, I believe the OP is still sitting in front of his computer looking for a solution :)

Log in to reply