Reputation: 31
I am trying to make a custom widget in Qt Creator that supports dragging objects around. At its simplest form, the widget has a QRect (or any other shape), on which I can click and then drag it around the widget. Once I release the mouse button, the QRect should stop being dragged.
In my QWidget class, I have this method
void ImageArea::mouseMoveEvent(QMouseEvent *event)
{
QPoint mousePos = event->pos();
qDebug() << mousePos.x();
qDebug() << mousePos.y();
qDebug() << "---------";
}
that can get the coordinates of the mouse as the pointer is moved around the screen. I have tried updating member variables for x and y, and then painting the QRect via the paintEvent method, but this doesn't work.
Does anyone have any suggestions?
Upvotes: 3
Views: 2307
Reputation: 25155
To get mouse move events, you must set the QWidget::mouseTracking property to true:
ImageArea::ImageArea( QWidget* p ) : QWidget( parent ) {
...
setMouseTracking( true );
}
Upvotes: 2
Reputation: 2643
Be sure to use the moveTo method to move the rectangle. Setting the x,y position directly may affect the size of the rectangle.
I don't see what you aren't doing, based on your question. Are you sure that the rectangles are in new positions when you paint them?
Maybe you are missing the update step Jeremy Friesner told to implement.
It seems that you are missing mouse button tracking. The easy way might be to get the mouse button states from QApplication::mouseButtons(). Although it might be slightly less efficient.
Upvotes: 0
Reputation: 73041
Implement paintEvent(QPaintEvent *) to draw the object(s) at the positions indicated by the current value(s) of their corresponding member variables.
After you've changed the values of one or more member variables (in mouseMoveEvent or wherever), call this->update(). That will tell Qt that it needs to call your paintEvent method again in the near future.
That should be all you need to do.
Upvotes: 0