Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving object with mouse

Tags:

qt

qlabel

drag

I use Qt and I want to move some object with mouse. For example, user clicks on object and drag this object to another place of window. How I can do it?

I tried mouseMoveEvent:

void QDropLabel::mouseMoveEvent(QMouseEvent *ev)
{
    this->move(ev->pos());
}

but unfortunately object moves very strange way. It jumps from place to place.

QDropLabel inherits QLabel. Also it has given a pixmap. I tried to do it with different objects, but result is same.

like image 781
LosYear Avatar asked Jun 23 '12 19:06

LosYear


People also ask

How do I make objects move with my mouse?

The basic method of dragging and dropping an object with the mouse in Unity typically involves adding a Collider component to the object and then using a physics function, such as Overlap Point or Raycast to detect when it's clicked.


1 Answers

Your movable widget must have a QPoint offset member. It will store a position of the cursor click relative to the widget's top left corner:

void DropLabel::mousePressEvent(QMouseEvent *event)
{
    offset = event->pos();
}

On mouse move event you just move your widget in its parent coordinate system. Note that if you don't subtract offset from the cursor position, your widget will 'jump' so its top left corner will be just under the cursor.

void DropLabel::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        this->move(mapToParent(event->pos() - offset));
    }
}
like image 59
hank Avatar answered Oct 07 '22 00:10

hank