Moving object with mouse

后端 未结 1 1166
误落风尘
误落风尘 2021-01-13 05:13

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 mous

相关标签:
1条回答
  • 2021-01-13 05:37

    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));
        }
    }
    
    0 讨论(0)
提交回复
热议问题