I am trying to understand how to handle various events with Qt and have found an issue I cannot understand with key modifiers e.g. Ctrl Shift Alt etc. I have made a default Qt GUI Application in Qt Creator extending QMainWindow and have found that the following example does not produce understandable results.
void MainWindow::keyPressEvent(QKeyEvent *event)
{
qDebug() << "Modifier " << event->modifiers().testFlag(Qt::ControlModifier);
qDebug() << "Key " << event->key();
qDebug() << "Brute force " << (event->key() == Qt::Key_Control);
}
Using the modifiers() function on the event never is true while the brute force method returns the correct value.
What have I done wrong?
The modifier key is held down while another key is pressed one or more times. For example, a modifier key is used to move the cursor across text a word or sentence at a time, and it is used to enter commands such as print, open and close. For Windows PCs, see Control key, Alt key and Windows key.
On an IBM compatible computer, modifier keys include Alt, Ctrl, Shift, and the Windows key. On the Apple Macintosh computer, the Control, Option, Command, and Shift keys are modifier keys. Additionally, most laptop and some desktop keyboards contain an Fn modifier key.
The Fn key, short form for function, is a modifier key on many keyboards, especially on laptops, used in a compact layout to combine keys which are usually kept separate. It is typically found on laptops due to their keyboard size restrictions.
Try using this to check for shift:
if(event->modifiers() & Qt::ShiftModifier){...}
this to check for control:
if(event->modifiers() & Qt::ControlModifier){...}
and so on. That works well for me.
EDIT:
To get the modifiers of a wheel event, you need to check the QWheelEvent
object passed to your wheelEvent()
method:
void MainWindow::wheelEvent( QWheelEvent *wheelEvent )
{
if( wheelEvent->modifiers() & Qt::ShiftModifier )
{
// do something awesome
}
else if( wheelEvent->modifiers() & Qt::ControlModifier )
{
// do something even awesomer!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With