Disconnecting lambda functions in Qt5

前端 未结 3 2039
攒了一身酷
攒了一身酷 2020-12-08 09:35

Is it possible to disconnect a lambda function? And if \"yes\", how?

According to https://qt-project.org/wiki/New_Signal_Slot_Syntax I need to use a QMetaObjec

3条回答
  •  渐次进展
    2020-12-08 10:31

    If you capture conn directly, you're capturing an uninitialised object by copy, which results in undefined behaviour. You need to capture a smart pointer:

    std::unique_ptr pconn{new QMetaObject::Connection};
    QMetaObject::Connection &conn = *pconn;
    conn = QObject::connect(m_sock, &QLocalSocket::readyRead, [this, pconn, &conn](){
        QObject::disconnect(conn);
        // ...
    }
    

    Or using a shared pointer, with slightly greater overhead:

    auto conn = std::make_shared();
    *conn = QObject::connect(m_sock, &QLocalSocket::readyRead, [this, conn](){
        QObject::disconnect(*conn);
        // ...
    }
    

    From Qt 5.2 you could instead use a context object:

    std::unique_ptr context{new QObject};
    QObject* pcontext = context.get();
    QObject::connect(m_sock, &QLocalSocket::readyRead, pcontext,
        [this, context = std::move(context)]() mutable {
        context.release();
            // ...
     });
    

提交回复
热议问题