Qt connect works, what is the equivalent disconnect method?

580 views Asked by At

I have a connect that works which connects a signal in C++ to a slot in JavaScript:

    Object::connect(this, &clsQtPushBtn::clicked
                   ,[pobjScriptEng, strCall, strFile, strScript]() {
                       QString strScriptWithCall = static_cast<QString>(strStript)
                                                 + static_cast<QString>(strCall) + "();";
                       pobjScriptEng->evaluate(strScriptWithCall);
                   });

In the above code:

this is an instance of my PushButton class clsQtPushBtn. clsQtPushBtn::clicked is the address of the "clicked" signal. pobjScriptEng is a pointer to an instance of QJSEngine*. strCall is a JavaScript function "test". strFile is the name of the JavaScript file "simon2.js". strScript is the content of the JavaScript file which contains the function test().

The question is how do a make the equivalent disconnect call as I'm having difficulty with it, there are 7 options and just changing connect for disconnect does not work, I get:

    no matching member function for call to 'disconnect'
2

There are 2 answers

0
Szymon Janora On BEST ANSWER

The QObject::connect function returns a QMetaObject::Connection so you can pass it to QObject::disconnect.

0
paxdiablo On

Normally, you would just provide the same details as in the connect call (for example, source and target objects, source signal and target slot).

However, that particular connect form you're using returns a QMetaObject::Connection object which you can store for later disconnection:

auto connection = Object::connect(this, &clsQtPushBtn::clicked, blah, blah);
:
QObject::disconnect(connection);

That's most likely a better way, since it can get the information immediately rather than searching for a connection in a possibly large list (though I may be wrong about how that's implemented). It's especially better since I believe it's the only option in this case, seeing that every lambda is unique, so you couldn't use a new one to find the old connection anyway.

In addition, I've used a local variable to store it but you'd probably be better storing it into a member variable of some sort.