[Qt-creator] Getting results from network in LocatorFilter

Jaroslaw Kobus Jaroslaw.Kobus at qt.io
Tue Mar 9 10:04:56 CET 2021


Hi Mikhail,

1. The results of your processing should be returned in matchesFor() function, as a return value. Please note, that this function is invoked in non-main thread.
2. Right, you should create network manager and requests for it in the same thread, as well as reading from replies should be done in the same thread. There is also a helpful virtual method of ILocatorFilter: prepareSearch(), which is invoked in the main thread, and it's being guaranteed that it will always precede a call to matchesFor() in other thread (matchesFor() will be called after prepareSearch() has finished). I think that something similar to your case is done inside WorkspaceLocatorFilter. The prepareSearch() could start the QNetworkRequest and connect to its QNetworkReply::finished signal, when the signal comes we collect the result and mark the flag, meaning we have received the reply. This would be main thread. And matchesFor() could just check if the flag was set - in this case we return the result collected in main thread, otherwise we wait for it with additional event loop.

Jarek

________________________________________
From: Qt-creator <qt-creator-bounces at qt-project.org> on behalf of Mikhail Bryukhovets <push.uni at gmail.com>
Sent: Sunday, March 7, 2021 11:16 AM
To: qt-creator at qt-project.org
Subject: [Qt-creator] Getting results from network in LocatorFilter

Hello!

I am trying to add suggestions functionality to my QtCerator plugin: When user types search request in the locator there will be a displayed list of suggested search queries based on entered text. Similar as it is done in browsers or search engines. Suggestions are obtained from network as results of GET requests to remote server. For example:
QNetworkRequest request;
request.setUrl(QUrl::fromUserInput("https://example.com/user_input?action=suggest"));
auto reply = network_manager_.get(request);
QObject::connect(reply, &QNetworkReply::readyRead, [&](){
    qDebug() << "reply:" << reply->readAll();
});

So as I understand it I should make a network request inside matchesFor() function of my class derived from Core::ILocatorFilter.
The first issue is: How and where do I obtain a result of a request to return it to the user?
The second is: It seems that QNetworkAccessManager can't process QNetworkRequest created in another thread (QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0x163c4d0), parent's thread is QThread(0x6cc0d0), current thread is QThread(0x28b5810))
I didn't find similar cases in plugins provided with QtCreator so I hope someone can point me in the right direction.

Mikhail.


More information about the Qt-creator mailing list