[Interest] QNetworkReply lambdas?

Jason H jhihn at gmx.com
Wed Jun 2 16:41:11 CEST 2021


I'm trying to figure out a more flexible way to do QNetworkReply. Ideally this would be through some async/await but I don't think Qt is "there" yet. (C++20 defines async/await, but there is not a library yet, and even Qt6 doesn't target C++20). So the callback lambda handler looks like the best option for now.

I have a QObject derived class, with a post() function. It takes an endpoint, and object (to be converted to JSON) and a lambda. Example:
remoteCloud->post("/login", credentials, [=](QNetworkReply* reply){
	if (reply->error() == QNetworkReply::NoError) {
		update("cartridge",
			   {{"synced", QDateTime::currentDateTime()}},
			   {{"cartridgeId", map["cartridgeId"]}});
	}
	reply->deleteLater();
});

With an implementation of:
template<typename F>
QNetworkReply *RemoteCloud::post(const QString& endpoint, const QVariantMap& item, F &lambda) {
	QNetworkReply* reply = m_nam.post(QNetworkRequest(endpoint), JSON(item));
	connect(reply, &QNetworkReply::finished, lambda);
	return reply;
}


Note that a lot of the Qt examples use a connect statement like this:
connect(reply, &QNetworkReply::finished, [request, reply](){ ... });

But when I tried to set this up, I either got static assert errors or l-value errors.

However I am trying to go one better and have my RemoteCloud::post set up the connect with the lambda. Is this possible?



More information about the Interest mailing list