tfl
tfl

Reputation: 1011

How to detect the modifier key on mouse click

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?

Upvotes: 39

Views: 32309

Answers (5)

user362638
user362638

Reputation:

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

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

Upvotes: 40

František Žiačik
František Žiačik

Reputation: 7614

From Qt Documentation — QMouseEvent Class:

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

Upvotes: 11

Dawoon Yi
Dawoon Yi

Reputation: 436

if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) == true) {

Upvotes: 3

tfl
tfl

Reputation: 1011

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);
}

Upvotes: 4

Martin Delille
Martin Delille

Reputation: 11810

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.

Upvotes: 12

Related Questions