Search code examples
qtqmlvirtual-keyboardqtvirtualkeyboard

How to get signal key pressed on QT virtual keyboard and play a sound click track?


in my QT application for embedded device , i want play a sound on key pressed event of the QML virtualkeyboard . Can I get this event? and How get it? I already have a class that play sound ( click effect) when a button was clicked that i use in the others qml pages

import QtQuick 2.7
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.3
import QtQuick.VirtualKeyboard 2.1

Page{
    id: pag
    width:  1280
    height: 800
    background:  Rectangle { color: "black"} 
    TextField {
        id: txtName
        height: 200
        width:200
        anchors.horizontalcenter:parent.horizontalCenter
        font.family: "Arial
            font.pixelSize: 24
             placeholderText: "insert your text here"
            background: Rectangle {
                anchors.fill: parent
                color: "transparent"
            }
    }
    InputPanel {
        id: virtualkeyboard
        width: 0.95*parent.width
        anchors.bottom: parent.bottom
    }
}

Solution

  • You can create a class Mykeyfilter, it's a QObject class

    then in your file .h you declare:

    bool eventFilter(QObject *object, QEvent *event);
    

    Then in your Mykeyfilter.cpp file you define eventFilter like this:

    bool MykeyFilter::eventFilter(QObject *object, QEvent *event)
    {
        switch(event->type())
        {
        case QEvent::KeyPress:
        case QEvent::KeyRelease:
            {
             //////call your sound class here that you want to play/////
             qDebug()<<"I have clicked"  //For testing
            }
        default:
            break;
    
            //         return QObject::eventFilter(object, event);
        }
    
        return QObject::eventFilter(object, event);
    
    }
    

    Also add in your main.cpp file:

    #include "mytouchfilter.h"
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
    
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
        app.installEventFilter(new MykeyFilter());
    
        return app.exec();
    }