How to detect the modifier key on mouse click
Asked Answered
S

5

39

I have a QTableWidget and would like that pressing Ctrl while clicking on a column header, marks the whole column.

To get the column index is not a problem, since there is a sectionPressed signal, which gives me the current index of the column clicked.

How can I get the state of any keyboard modifiers when a column is clicked?

Seely answered 23/6, 2010 at 8:35 Comment(0)
E
40

On Qt 4, try QApplication::keyboardModifiers().

The Qt 5 and Qt 6 equivalent is QGuiApplication::keyboardModifiers().

Ethereal answered 23/6, 2010 at 13:30 Comment(0)
S
12

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.

Sabol answered 2/9, 2014 at 13:26 Comment(0)
W
11

From Qt Documentation — QMouseEvent Class:

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

Watering answered 23/6, 2010 at 8:38 Comment(0)
S
4

I have to install an eventFilter and remove the sectionPressed handler:

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

Within the eventFilter, I can check whether 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);
}
Seely answered 23/6, 2010 at 9:46 Comment(0)
D
3
if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) == true) {
Diabolize answered 18/10, 2013 at 3:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.