【发布时间】:2016-04-01 09:32:23
【问题描述】:
我是我的主线程,我有一个 Qt 窗口正在运行,它正在调用我的后台线程(网络服务),并最终期待应该反映在 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());
});
}
网络服务如下:
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);
}
它是如何工作的?它甚至可以工作吗?
我知道你可以使用QMetaObject::invokeMethod(this, "method", Qt::QueuedConnection在主线程中调用一个函数,所以我尝试了以下方法:
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_));
}
如何在此处将 responseMsg 作为 _delegate 的参数传递?
void QTServer::runInMainThread(std::function<void(std::shared_ptr<message>)> f) {
f();
}
如何摆脱“No function with these arguments”错误?
【问题讨论】:
标签: c++ multithreading qt