Im my mainthread, I have a Qt window running, which is calling my background thread (network service) and is eventually expecting responses which should be reflected in the UI:
// runs in main (GUI) thread
void QTServer::onButtonClick(){
srv->request(msg,
[this]
(std::shared_ptr<message> msg){
this->ui.txtResponse->setText("received a response" + msg.data());
});
}
The network service is as follows:
std::function<void(std::shared_ptr<message>)> delegate_;
void NetworkService::request(message& msg,std::function<void(std::shared_ptr<message> msg)> fn)
{
// send the request to the socket and store the callback for later
// ...
this->delegate_ = fn;
}
void NetworkService::onResponseReceived(std::shared_ptr<message> responseMsg)
{
// is called from the background thread (service)
// Here I would like to call the lambda function that the service stored somewhere (currently as an std::func member)
// psuedo: call In Main Thread: delegate_(responseMsg);
}
How does that work? Does it even work?
I know that you can use QMetaObject::invokeMethod(this, "method", Qt::QueuedConnection
to call a function in the mainthread, so I tried the following:
void NetworkService::onResponseReceived(std::shared_ptr<message> responseMsg)
{
QMetaObject::invokeMethod(this, "runInMainThread", Qt::QueuedConnection, QGenericArgument(), Q_ARG(std::function<void(std::shared_ptr<message>)>, delegate_));
}
How do I pass the responseMsg here as an argument for _delegate?
void QTServer::runInMainThread(std::function<void(std::shared_ptr<message>)> f) {
f();
}
How to get rid of "No function with these arguments" error?