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
}
}
}
}