简体   繁体   中英

Disconnecting lambda functions in Qt5

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 QMetaObject::Connection which is returned from the QObject::connect method, but then how can I pass that object to the lambda function?

Pseudo-code example:

QMetaObject::Connection conn = QObject::connect(m_sock, &QLocalSocket::readyRead, [this](){
    QObject::disconnect(conn); //<---- Won't work because conn isn't captured

    //do some stuff with sock, like sock->readAll();
}

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<QMetaObject::Connection> 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<QMetaObject::Connection>();
*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<QObject> context{new QObject};
QObject* pcontext = context.get();
QObject::connect(m_sock, &QLocalSocket::readyRead, pcontext,
    [this, context = std::move(context)]() mutable {
    context.release();
        // ...
 });

The context solution from ecatmur's answer is the easiest option, but I think the use of the smart pointer makes it hard to understand. I prefer to use a raw pointer instead:

QObject *context = new QObject(this);
connect(sender, &Sender::signal, context, [context] {
  delete context;
  // ...
});

You can define the conn as a private variable in the .h file. QMetaObject::Connection conn .
in the lambda function, you can use conn and disconnect it.

 conn = QObject::connect(m_sock, &QLocalSocket::readyRead, [=](){
    QObject::disconnect(conn); //<---- Won't work because conn isn't captured

    //do some stuff with sock, like sock->readAll();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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