Draggable QPushButton Flicker?



  • I'm a newbie with QT and I tried to implement a draggable QPushButton like so:

    void DragButton::mousePressEvent(QMouseEvent* event)
    {
        dragging = true;
    }
    
    void DragButton::mouseMoveEvent(QMouseEvent* event)
    {
        if (dragging)
            move(event->pos());
    }
    
    void DragButton::mouseReleaseEvent(QMouseEvent* event)
    {
        dragging = false;
    }
    

    Note: DragButton inherits QPushButton.
    I loved this solution as it's very simple and intuitive. However it doesn't work like expected. Here are the results as a gif:
    alt text
    I haven't been able to find a good solution. What could be causing this flicker?



  • If you look at QMouseEvent class documentation you'll find this:
    const QPoint & QMouseEvent::pos() const

    Returns the position of the mouse cursor, relative to the widget that received the event.

    If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.

    So solution would be to use globalPos or relative coordinates to parent widget here's the implementation of the latter:

    void DragButton::mouseMoveEvent(QMouseEvent *e)
    {
        if(e->buttons() & Qt::LeftButton)
            move(mapToParent(e->pos()));
    }
    

Log in to reply