Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle key events Ctrl+Tab and Ctrl+Shift+Tab

I want to handle the two key events Ctrl+Tab and Ctrl+Shift+Tab in order to switch between tabs in my application ("forward" and "backward" respectively). However, this doesn't seem to work as expected.

This is my current code (minimal example):

import QtQuick 1.1

Item {
    width: 100
    height: 100

    focus: true

    Keys.onPressed: {
        if(event.modifiers & Qt.ControlModifier) {
            if(event.key === Qt.Key_Tab) {
                if(event.modifiers & Qt.ShiftModifier)
                    console.log('backward')
                else
                    console.log('forward')
            }
        }
    }
}

I ran this piece of code with qmlviewer (Qt version 4.8.2)

Output when pressing Ctrl+Tab:

forward
forward

Output when pressing Ctrl+Shift+Tab:

none

So I see two errors: The former key sequence is handled twice while the other one not at all.

  • EDIT: The reason that the other one doesn't get handled at all is solved, see comments.

Why does this happen and how can I solve this?

Note: I already use Qt Components for Desktop in my application, so it's OK if you know a solution requiring this module.

like image 292
leemes Avatar asked Oct 11 '12 01:10

leemes


1 Answers

You have to accept the event, otherwise the event is propagated to the parents until it is accepted. The following code worked for me.

Item {
    width: 100
    height: 100

    focus: true

    Keys.onPressed: {
        if(event.modifiers && Qt.ControlModifier) {
            if(event.key === Qt.Key_Tab) {
                console.log('forward')
                event.accepted = true;
            }
            else if(event.key === Qt.Key_Backtab) {
                console.log('backward')
                event.accepted = true;
            }
        }
    }
}

Edit: This behavior lets parents handle events that the child could not, for things like hotkeys.

Hope this helps!

like image 123
Mevos Avatar answered Nov 15 '22 09:11

Mevos