Reputation: 1011
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
Reputation:
On Qt 4, try QApplication::keyboardModifiers()
.
The Qt 5 and Qt 6 equivalent is QGuiApplication::keyboardModifiers()
.
Upvotes: 40
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
Reputation: 436
if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) == true) {
Upvotes: 3
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
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