在Android上,当用户在虚拟键盘上键入按键时,我没有按键事件。当用户按下“完成”按钮并且键盘关闭时,我得到了它们。但是要实现一些交互行为,我必须在用户键入密钥时获取它们。所以我尝试注册一个事件过滤器:
bool EventFilter::eventFilter(QObject *watched, QEvent *event ) {
//qDebug() << "eventfilter: " << event->type() ;
if (!watched) {
return false;
}
if (!event) {
return false;
}
if (watched->objectName() == "myedit") {
qDebug() << "Field textedit edited: type="<< event->type();
if (event->type() == QEvent::InputMethod) {
QInputMethodEvent *inputMethod = static_cast<QInputMethodEvent *>(event);
qDebug() << "inputMethod received";
if (!inputMethod) {
qDebug() << "Unable to cast correct type";
} else {
QString commit = inputMethod->commitString();
qDebug() << "commit str:" << commit;
QList<QInputMethodEvent::Attribute> list= inputMethod->attributes();
qDebug() << "attributes:";
for (int i=0;i<list.size();i++) {
QInputMethodEvent::Attribute attr=list.at(i);
QVariant var=attr.value;
qDebug() << i << ": type=" << attr.type << var.toUrl();
}
}
}
}
return false;
}
现在,当我在虚拟键盘中键入按键时,我会收到以下事件:
D MyApp: ../MyApp/eventfilter.cpp:18 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): Field textedit edited: type= QEvent::Type(InputMethodQuery)
D MyApp: ../MyApp/eventfilter.cpp:18 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): Field textedit edited: type= QEvent::Type(InputMethod)
D MyApp: ../MyApp/eventfilter.cpp:21 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): inputMethod received
D MyApp: ../MyApp/eventfilter.cpp:26 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): commit str: ""
D MyApp: ../MyApp/eventfilter.cpp:28 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): attributes:
D MyApp: ../MyApp/eventfilter.cpp:32 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): 0 : type= 1 QUrl("")
D MyApp: ../MyApp/eventfilter.cpp:32 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): 1 : type= 0 QUrl("")
D MyApp: ../MyApp/eventfilter.cpp:18 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): Field textedit edited: type= QEvent::Type(InputMethodQuery)
D MyApp: ../MyApp/eventfilter.cpp:18 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): Field textedit edited: type= QEvent::Type(InputMethodQuery)
D MyApp: ../MyApp/eventfilter.cpp:18 (virtual bool EventFilter::eventFilter(QObject*, QEvent*)): Field textedit edited: type= QEvent::Type(InputMethodQuery)
不幸的是,这种方法没有得到我预期的结果,因为我认为虚拟键盘会发送QKeyEvent对象,并且我很容易获得键码,但是它会发送InputMethod
和InputMethodQuery
:(
当用户以某种方式在虚拟键盘中键入键码时,能否获得键码?
我正在使用Qt 5.11