开发者

How to detect the modifier key on mouse click in Qt

I have a QTableWidget and would like that pressing CTRL while cl开发者_如何学运维icking 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?


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


This works for me.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜