简体   繁体   English

如何检测Qt中是否同时按下了两个鼠标按钮?

[英]How to detect if both mouse buttons are pressed in Qt?

Right now I'm able to detect when only one button is clicked. 现在,我能够检测到何时仅单击一个按钮。 But I want to detect when both are pressed together. 但是我想检测一下两者是否同时按下。 The purpose is to select some items from a QTableView. 目的是从QTableView中选择一些项目。 I'm trying to select them in such a way that when left button is clicked on an item while right button is already kept pressed then the item will be among the selected. 我试图以这样的方式选择它们:当在某个项目上单击鼠标左键时,同时一直按住鼠标右键,则该项目将处于选中状态。

The following code only shows the message that the right button is clicked, but it doesn't show that both the buttons are clicked. 以下代码仅显示单击右键的消息,但不显示两个按钮都单击的消息。 How can I manage to detect when both of them are clicked? 我如何设法检测何时都单击了它们?

bool MainWindow::eventFilter(QObject* obj, QEvent *ev)
{
    if(obj = ui->listOfImages->viewport())
    {
        QMouseEvent * mouseEv = static_cast<QMouseEvent*>(ev);
        if(mouseEv->buttons() == Qt::RightButton)
        {
            qDebug()<<"Right Button clicked!";
            if(mouseEv->buttons() == Qt::LeftButton)
            {
                qDebug()<<"Both button clicked!";
                return QObject::eventFilter(obj,ev);
            }
        }
    }
    return QObject::eventFilter(obj,ev);
}

Thanks. 谢谢。

Try 尝试

if( (mouseEv->buttons() & Qt::RightButton) &&
    (mouseEv->buttons() & Qt::LeftButton) )
{
...
}

Hint: 暗示:

When you just checked buttons() is equal to Qt::RightButton, how could it be equal to Qt::LeftButton? 当您刚刚检查button()等于Qt :: RightButton时,怎么可能等于Qt :: LeftButton?

The QMouseEvent::buttons() function returns a combination of OR'd states of the mouse buttons. QMouseEvent :: buttons()函数返回鼠标按钮OR状态的组合。 Therefore, to test the left button is pressed, you should be doing this: - 因此,要测试是否按下了左按钮,您应该这样做:-

if(mouseEv->buttons() & Qt::LeftButton)

and for the right button: - 并为右键:-

if(mouseEv->buttons() & Qt::RightButton)

As the Qt docs state: - 如Qt docs所述:-

For mouse press and double click events this includes the button that caused the event. 对于鼠标按下和双击事件,这包括导致事件的按钮。 For mouse release events this excludes the button that caused the event. 对于鼠标释放事件,这不包括引起事件的按钮。

So you can keep track of when buttons are held down and released. 因此,您可以跟踪按下和释放按钮的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM