私のメインスレッドは、バックグラウンドスレッド(ネットワークサービス)を呼び出すQtウィンドウを実行していて、最終的に応答を期待しています。 UI:次のようにバックグラウンドスレッドからメインUIスレッドのlambda/std :: functionを呼び出す
// 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);
}
そのしくみを教えてください。それは機能するのでしょうか?
私はあなたがmainthreadで関数を呼び出すために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_));
}
にはどうすれば_delegateの引数として、ここでresponseMsgを渡すのですか?
void QTServer::runInMainThread(std::function<void(std::shared_ptr<message>)> f) {
f();
}
「これらの引数で機能していません」というエラーを取り除くにはどうすればよいですか?
うーん、それは私が 'Q_ART(ボイド*、delegate_)' – netik
パスアドレスQ_ARG(ボイド*、&delegate_)しようとした場合、その後、reinterpret_castは<*のボイド(STD :: shared_ptrのを)>を使用し、 "なしコンストラクタが利用できる" と言います –
jonezq