繁体   English   中英

在Qt中发布到窗口时,事件将从队列中删除

[英]Event gets deleted from queue when posted to window in Qt

我正在尝试将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();
}

当您的QKeyEvent event对象超出范围时(在您的情况下,函数结束),它将被销毁。 docs声明: Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately.

and: 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. 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.

因此,您应该使用new创建QKeyEvent对象:

QKeyEvent *event = new QKeyEvent(QKeyEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM