我正在尝试将自定义QKeyEvent
(如Keypress key BTextField
)发送到我的QML 文件中的项目(如) 。这是我写的,它不起作用。似乎项目 ( TextField
) 没有得到我的事件(我假设这是因为B
我的文本没有附加任何字符TextField
)。我在课堂上捕获信号,click
然后ClickHandler
在我的handleClick
插槽中,我尝试向我发布一个自定义event
,focused item
这里是一个TextField
.
点击处理程序.h
class ClickHandler : public QObject
{
Q_OBJECT
QQmlApplicationEngine* engine;
QApplication* app;
public:
explicit ClickHandler(QQmlApplicationEngine *,QApplication* app);
signals:
public slots:
void handleClick();
};
ClickHandler.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);
}
主.cpp:
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();
}
main.qml:
ApplicationWindow {
objectName: "rootWindow"
visible: true
Column {
TextField {
id: textId1
objectName: "text1"
text: "text1 message"
focus: true
}
TextField {
id: textId2
objectName: "text2"
text: "text2 message"
}
Button {
objectName: "button"
text : "Click me";
}
}
}