我正在尝试将KeyPress事件发送到我的窗口应用程序:
QtQuick2ApplicationViewer viewer;
当我按下GUI中的按钮将标签KeyPress事件发送给查看器时,我收到错误:
Tab Enter
QCoreApplication::removePostedEvent: Event of type 6 deleted while posted to QtQuick2ApplicationViewer
我们可以看到SimKeyEvent :: pressTab()被触发,因为在调试窗口中打印了“Tab Enter”。
为什么我的事件会从事件队列中删除?
SimKeyEvent.h:
class SimKeyEvent : public QObject
{
Q_OBJECT
public:
explicit SimKeyEvent(QObject *parent = 0, QtQuick2ApplicationViewer *viewer = 0);
private:
QtQuick2ApplicationViewer *viewer;
signals:
public slots:
void pressTab();
};
SimKeyEvent.cpp:
SimKeyEvent::SimKeyEvent(QObject *parent, QtQuick2ApplicationViewer *viewer) :
QObject(parent)
{
this->viewer = viewer;
}
void SimKeyEvent::pressTab()
{
qDebug() << "Tab Enter"; //To confirm that this slot gets called.
QKeyEvent event = QKeyEvent(QKeyEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
QCoreApplication::postEvent(viewer, &event);
}
main.cpp中:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/GC/MainMenu.qml"));
SimKeyEvent *simKeyEvent = new SimKeyEvent(0, &viewer);
QObject *object = viewer.rootObject();
QObject::connect(object, SIGNAL(pressTab()), simKeyEvent, SLOT(pressTab()));
viewer.showMaximized();
return app.exec();
}
答案 0 :(得分:3)
当QKeyEvent event
对象超出范围时(在函数结束时),它将被销毁。
docs说明了这一点:Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately.
和:The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted.
因此,您应该使用QKeyEvent
创建new
对象:
QKeyEvent *event = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);