QML – Switch button is controlled by spacebar – why?

Question:

In my Pyside/QML application I want to use spacebar onPressed event for my purpose – it works. When add to my app Switch button, then the spacebar button controls the Switch instead of calling my onPressed event.
Is there any way to disable the Switch from being controlled by the spacebar button?

  1. Spacebar catch event:
Item {
        anchors.fill: parent
        focus: true
        Keys.onPressed: (event)=> {
            
                if (event.key == Qt.Key_Space) {
                    backend.btnStartFlash();
                    event.accepted = true;
                }
            }
        }
  1. Switch button
 Switch {
                    id: switchBtn
                    text: qsTr("mode")
                    font.pixelSize: 16
                    font.bold: false
                    font.italic: true
                    checked:false
}

Asked By: WITC

||

Answers:

A solution would be to send the space events from the Switch back to the Item as follows:

    Item {
        id: thisItem
        anchors.fill: parent
        focus: true
        Keys.onPressed: (event) => {
            if (event.key == Qt.Key_Space) {
                backend.btnStartFlash();
                event.accepted = true;
            }
        }
    }

    // ...

    Switch {
        id: switchBtn
        text: qsTr("mode")
        font.pixelSize: 16
        font.bold: false
        font.italic: true
        checked:false
        Keys.onPressed: (event) => {
            if (event.key == Qt.Key_Space) {
                thisItem.forceActiveFocus();
            }
        }
    }
Answered By: Stephen Quan

This is caused by the focus property of the Switch. When you click it, it takes over the focus. Either you set the focus property of the Switch to false and the focus of the Itemto true at some point to get back the focus on the Item or you don’t allow the Switch to never get focus with the focusPolicy property (focusPolicy documentation).

One remark: You should use === for comparison in JavaScript. You could also use the Keys.onSpacePressed directly to avoid the if statement (spacePressed documentation).

import QtQuick
import QtQuick.Controls

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Item {
        anchors.fill: parent
        focus: true
        Keys.onSpacePressed: (event)=> {
            console.log("Space pressed")
            event.accepted = true
        }
    }

     Switch {
        id: switchBtn
        text: qsTr("mode")
        font.pixelSize: 16
        font.bold: false
        font.italic: true
        checked: false
        focusPolicy: Qt.NoFocus
    }
}
Answered By: iam_peter
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.