How to detect the modifier key on mouse click in Qt

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?

Answers


Try QApplication::keyboardModifiers() which is always available

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


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


You can use QGuiApplication::queryKeyboardModifiers() which is simpler to use:

if(QGuiApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier))
{
    // Do a few things
}

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

This works for me.

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

Need Your Help

AngularJs sort object in ngRepeat

angularjs angularjs-ng-repeat

I'm using AngularJs and found a problem in ordering properties of a hash object in a template.