Qt Quick 鍵盤操作

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView viewer;
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);
    viewer.setSource(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject::connect(viewer.engine(),SIGNAL(quit()), &app, SLOT(quit()));

    viewer.show();

    return app.exec();
}
main.qml

import QtQuick 2.6
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.0
import QtQuick.Dialogs 1.1

Rectangle {
    width: 300
    height: 200
    color: "gray"

    Button {
        text: "quit"
        anchors.centerIn: parent
        onClicked: {
            Qt.quit()
        }
    }

    Text {
        id: showText
        anchors.top: parent.top
        anchors.topMargin: 10
        anchors.horizontalCenter: parent.horizontalCenter
        font.pixelSize: 20
        color: "red"
    }

    Item {
        focus: true
        Keys.enabled: true
        Keys.onEscapePressed: {
            Qt.quit()
        }
        Keys.onDownPressed: {
            showText.text += "Down"
        }
        Keys.onUpPressed: {
            showText.text += "Up"
        }
        Keys.onRightPressed:  {
            showText.text += "Right"
        }
        Keys.onLeftPressed: {
            showText.text += "Left"
        }
        Keys.onSpacePressed: {
            showText.text += "Space"
        }
        Keys.onPressed: {
            switch(event.key) {
            case Qt.Key_0:
                showText.text += 0
                break
            default:
                showText.text += "No"
                break
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章