正确的点击事件

Proper click event

我有像这样的无边框按钮

问题是我无法点击按钮。仅当我执行双击而不改变按钮上的位置时它才有效。如何检查我执行点击(而不是拖动)的用户?

代码来了:

bool LoginForm::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QMouseEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (obj == ui.loginButton)
        {
            QPoint absPos = ui.loginButton->mapToParent(QPoint(0, 0));
            m_dragPosition = (mouseEvent->pos() + absPos);
            return true;
        }
    }
    return false;
}

void LoginForm::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {   
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void LoginForm::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        QPoint coord = event->globalPos() - m_dragPosition;
        move(coord);
        event->accept();
    }
}

How to check that user is performing click (not drag)?

应该更容易。不要从您的按钮中窃取事件。这种方法是从 Qt 示例中借用的:Music Player. See musicplayer.cpp for details.

void LoginForm::mousePressEvent(QMouseEvent *event)
{
    m_dragPosition = event->globalPos() - pos();
    event->accept();
}


void LoginForm::mouseMoveEvent(QMouseEvent *event)
{
    move(event->globalPos() - m_dragPosition);
    event->accept();
}


void LoginForm::mouseReleaseEvent(QMouseEvent *event)
{
    m_dragPosition = QPoint();
    event->accept();
}

最简单的方法是禁用拖动按钮 bool

LoginForm::LoginForm(QWidget *parent)
    : QWidget(parent)
{
    ...
    m_isDragButton = false;
} 

LoginForm::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QMouseEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (obj == ui.loginButton)
            m_isDragButton = true;
    }
    return false;
}
void LoginForm::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {   
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void LoginForm::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_isDragButton)
        if (event->buttons() & Qt::LeftButton)
        {
            QPoint coord = event->globalPos() - m_dragPosition;
            move(coord);
            event->accept();
        }
}

void LoginForm::mouseReleaseEvent(QMouseEvent *event)
{
    m_isDragButton = false;
    m_dragPosition = QPoint();
    event->accept();
}