1

My question is: How to check whether or not a connection exists in Qt when the slot is a lambda function?

I have the following code snippet

connect(item1, &Item::somethingChanged, this, [this](){ doSomething(m_someObject1, 2); }, Qt::DirectConnection);

connect(item2, &Item::somethingChanged, this, [this](){ doSomething(m_someObject2, 5); }, Qt::DirectConnection);

I want to check whether or not this connection exists within my GoogleTest:

ASSERT_FALSE(QObject::connect(item1, &Item::somethingChanged, this, [this](){ doSomething(m_someObject1, 2); }, Qt::UniqueConnection));

This however, does not work because the lambda slot is considered to be a different lambda than the one I connected within my class itself. How would I go about checking whether this connection exists?

1 Answers1

0

If I understand your question correctly, you can easily check if a sender-lambda connection exists/is connected with QMetaObject's Connection class. You can define a QMetaObject::Connection variable (let's say QMetaObject::Connection ourConnection) and set it's value to a connection. This variable is now a handle to that connection.

If ourConnection is set to a running connection instance, it would return true:

QMetaObject::Connection ourConnection = connect(ui->ourAction, &QAction::triggered, this, []{
     // Do stuff;
});
qDebug() << ourConnection; // returns true

If ourConnection is set to a disconnected connection instance, it would return false:

QMetaObject::Connection ourConnection = connect(ui->ourAction, &QAction::triggered, this, []{
     // Do stuff;
});
disconnect(ourConnection);
qDebug() << ourConnection; // returns false

If ourConnection is not set to a connection instance at all, it would return false:

QMetaObject::Connection ourConnection;
qDebug() << ourConnection; // returns false
Rakeeb Hossain
  • 353
  • 1
  • 11