Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the modifier key on mouse click in Qt

Tags:

qt

People also ask

Which key is the modifier key?

On a Windows keyboard, the modifier keys are Shift, Alt, Control, and the Windows key. On a Mac keyboard, the modifier keys are Shift, Control, Option, and Command (often called the Apple key).

What is modifier keys use?

The modifier key is held down while another key is pressed one or more times. For example, a modifier key is used to move the cursor across text a word or sentence at a time, and it is used to enter commands such as print, open and close. For Windows PCs, see Control key, Alt key and Windows key.


Try QApplication::keyboardModifiers() which is always available

On Qt 5, try QGuiApplication::keyboardModifiers().


If you are want to know the modifiers key state from a mouse click event, you can use QGuiApplication::keyboardModifiers() which will retrieve the key state during the last mouse event:

if(QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) {
    // Do a few things
}

Otherwise, if you want to query explicitly the modifiers state you should use QGuiApplication::queryKeyboardModifiers(). This might be required in other use case like detecting a modifier key during the application startup.


The state of the keyboard modifier keys can be found by calling the modifiers() function, inherited from QInputEvent.

http://doc.qt.io/qt-5/qmouseevent.html


this is really annoying, I have to install an eventFilter and remove the sectionPressed handler

ui->tableWidget->horizontalHeader()->viewport()->installEventFilter(this);

Within the eventFilter I can check wether a key was pressed like so

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        if(Qt::ControlModifier == QApplication::keyboardModifiers())
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if(mouseEvent)
            {
                if(mouseEvent->button()== Qt::LeftButton)
                {
                    ui->tableWidget->selectColumn(ui->tableWidget->itemAt(mouseEvent->pos())->column());
                    return true;
                }
            }
        }
    }

    return QWidget::eventFilter(object,event);
}