spikestar
spikestar

Reputation: 173

Qt mouseMoveEvent only when left mouse button is pressed

I currently have a program that draws lines and rectangles.

void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);

I use mouseMoveEvent to draw temporary preview of a line and when i release i draw the actual line. What I would like to know is how can i make mouseMoveEvent work work only when i have the left mouse button pressed down. I tried the following but then the whole function stops working.

void mouseMoveEvent(QMouseEvent *event)
{
     if(event->button() == Qt::LeftButton)
     {
        //do stuff
     }
}

but then the function doesn't do anything. Any assistance would be much appreciated

Upvotes: 9

Views: 14326

Answers (1)

cmannett85
cmannett85

Reputation: 22376

From the documentation of QMouseEvent::button():

Note that the returned value is always Qt::NoButton for mouse move events.

You should use buttons() instead.

if(event->buttons() & Qt::LeftButton)
{
    //do stuff
}

Upvotes: 21

Related Questions