欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt Quick 键盘操作

程序员文章站 2024-01-05 17:36:46
...
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
            }
        }
    }
}

 

上一篇:

下一篇: