Moving object with mouse

落花浮王杯 提交于 2019-12-01 04:00:15

问题


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.


回答1:


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));
    }
}


来源:https://stackoverflow.com/questions/11172420/moving-object-with-mouse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!