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.
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With