#include "menubutton.h"
#include <QDebug>

MenuButton::MenuButton(QWidget *parent)
    : QPushButton(parent),
      _mouseMove(false),
      _mousePress(false),
      _canMove(false),
      _movedItem(this)
{
}

void MenuButton::setMovedItem(QWidget *item)
{
    Q_ASSERT(item!=0);
    this->_movedItem = item;
}

void MenuButton::mousePressEvent(QMouseEvent *e)
{
    if (e->button()==Qt::LeftButton)
    {
        _mousePress = true;
        _lastMousePos = e->globalPos();
        _canMove = false;
    }

    QPushButton::mousePressEvent(e);
    return;
}

void MenuButton::mouseMoveEvent(QMouseEvent *e)
{
    if (_mousePress && (e->buttons()==Qt::LeftButton))
    {
        QPoint moved = e->globalPos() - _lastMousePos;
        // 防止因抖动误拖动
        if(_canMove || (abs(moved.x())>10 || abs(moved.y())>10)) {
            _movedItem->move(_movedItem->pos() + moved);

            _lastMousePos = e->globalPos();

            _mouseMove = true;
            _canMove = true;
        }
    }
    return;
}

void MenuButton::mouseReleaseEvent(QMouseEvent *e)
{
    if (e->button()==Qt::LeftButton)
    {
        _mousePress = false;
    }
    if(!_mouseMove)
    {
         QPushButton::mouseReleaseEvent(e);
    }

    _mouseMove = false;
    return;
}
