Qml全局按键
2018-11-29 本文已影响0人
zhengtianzuo
创建一个c++类 对事件进行监听
bool QmlKey::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Backspace)
{
emit sKeyBackPress();
return(true);
}
}
if (event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Backspace)
{
emit sKeyBackRelease();
return(true);
}
}
return QObject::eventFilter(watched, event);
}
注册并连接信号槽
QmlKey qmlKey;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("qmlKey", &qmlKey);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
QObject *root = engine.rootObjects()[0];
root->installEventFilter(&qmlKey);
QObject::connect(&qmlKey, SIGNAL(sKeyBackPress()), root, SLOT(onSKeyBackPress()));
QObject::connect(&qmlKey, SIGNAL(sKeyBackRelease()), root, SLOT(onSKeyBackRelease()));
Qml中信号槽:
function onSKeyBackPress(){
label.text = qsTr("按下了Backspace")
}
function onSKeyBackRelease(){
label.text = qsTr("松开了Backspace")
}
show.gif
需要完整代码请访问QtQuickExamples