我正在尝试将自定义QKeyEvent
(例如 Keypress键B )发送到 QML文件中的项目(例如TextField
)。这是我写的它不起作用。似乎项目(TextField
)没有得到我的事件(我假设这是因为我的B
文本中没有附加TextField
个字符。我在click
课程中捕获了ClickHandler
信号,然后在我的handleClick
广告位中,我尝试发布自定义{ {1}}到我的event
,其中focused item
。
ClickHandler.h
TextField
ClickHandler.cpp:
class ClickHandler : public QObject
{
Q_OBJECT
QQmlApplicationEngine* engine;
QApplication* app;
public:
explicit ClickHandler(QQmlApplicationEngine *,QApplication* app);
signals:
public slots:
void handleClick();
};
main.cpp中:
#include "clickhandler.h"
#include <QMessageBox>
#include <QQuickItem>
ClickHandler::ClickHandler(QQmlApplicationEngine* engine, QApplication* app)
{
this->engine = engine;
this->app = app;
}
void ClickHandler::handleClick()
{
QObject* root = engine->rootObjects()[0];
QQuickItem *item = (root->property("activeFocusItem")).value<QQuickItem *>();
if (item == NULL)
qDebug() << "NO item";
QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,Qt::Key_B,Qt::NoModifier);
QCoreApplication::postEvent(item,event);
}
main.qml:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject* root = engine.rootObjects()[0];
ClickHandler* ch = new ClickHandler(&engine, &app);
QQuickItem* button = root->findChild<QQuickItem*>("button");
QObject::connect(button, SIGNAL(clicked()), ch, SLOT(handleClick()));
return app.exec();
}
答案 0 :(得分:1)
如果您实施onPressed
处理程序,则可以查看问题所在。
ApplicationWindow {
objectName: "rootWindow"
visible: true
Column {
TextField {
id: textId1
objectName: "text1"
text: "text1 message"
focus: true
Keys.onPressed: {
console.log("textId1: " + event.key + " : " + event.text)
}
}
TextField {
id: textId2
objectName: "text2"
text: "text2 message"
Keys.onPressed: {
if (event.key === Qt.Key_B) {
console.log("I like B's but not QString's")
}
}
}
...
此代码打印qml: textId1: 66 :
,因为该密钥的文本为空。
您需要使用以下内容创建活动:
Qt::Key key = Qt::Key_B;
QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,
key,
Qt::NoModifier,
QKeySequence(key).toString());