C++ Qt如何检查按下了哪个鼠标按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16759544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:37:28  来源:igfitidea点击:

Qt how to check which mouse button is pressed

c++qtpyqtpyside

提问by Alex

I have problems in PySide while trying to determine which mouse button is pressed in event function. I need it in particular for ignoring mouse move event, because it's doing job on both mouse buttons, left and right.

在尝试确定事件函数中按下了哪个鼠标按钮时,我在 PySide 中遇到了问题。我特别需要它来忽略鼠标移动事件,因为它在左右鼠标按钮上都在工作。

I want to ignore mouse move event if the right button on scene is pressed. Any help?

如果按下场景上的右键,我想忽略鼠标移动事件。有什么帮助吗?

回答by fasked

All of mouse events have two methods (buttonand buttons) to determine which of buttons are pressed. But for only moveevent the documentation says:

所有鼠标事件都有两种方法 (buttonbuttons) 来确定按下了哪个按钮。但仅对于move事件,文档说:

Note that the returned value is always Qt::NoButton for mouse move events.

请注意,对于鼠标移动事件,返回值始终为 Qt::NoButton。

for mouseMoveEventyou should use buttonsmethod.

因为mouseMoveEvent你应该使用buttons方法。

void mouseMoveEvent(QMouseEvent *e)
{
    if(e->buttons() == Qt::RightButton)
        qDebug() << "Only right button";
}

In order to ignore move events you need to do this work in eventFilterof course.

为了忽略移动事件,你eventFilter当然需要做这项工作。

回答by ken

QApplication::mouseButtons()will return the status of mouseButton, so, you can get the status of mouse in KeyPressEvent.

QApplication::mouseButtons()将返回 的状态mouseButton,因此,您可以在 中获取鼠标的状态KeyPressEvent

回答by Shf

you can check, which mouse button is pressed via Qt::RightButton. Sorry for c++ code, but i hope, you would understand idea anyway:

您可以检查,通过 按下了哪个鼠标按钮Qt::RightButton。抱歉 C++ 代码,但我希望,无论如何你都会理解这个想法:

void mousePressEvent(QMouseEvent *event)
{ 
    if (event->button()==Qt::RightButton){
        qDebug() << "right button is pressed
    }
}

回答by Nicola

You could use a boolean:

您可以使用布尔值:

void mousePressEvent(QMouseEvent *event)
{ 
if (event->button()==Qt::RightButton){
    qDebug() << "right button is pressed
    pressed=true; //<-----
}
}

and on mouseMoveEvent

并在 mouseMoveEvent 上

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{

float dx = event->x() - lastPos.x();      // where lastpos is a QPoint member
float dy = event->y() - lastPos.y();

if (dx<0) dx=-dx;
if (dy<0) dy=-dy;

if (event->buttons() & Qt::LeftButton) {  //if you have MOVEd

     ...do something

}

if (event->buttons() & Qt::RightButton) {

    if (pressed==true) return;  
    else{
    ...do   
    } 
}
}

On mouserelease you have to set pressed=false; ( "pressed" must be a member of the class)

在鼠标释放时,您必须设置 press=false; (“pressed”必须是该类的成员)

Hope it helps,let me know

希望它有帮助,让我知道