简体   繁体   中英

Get function which initiated QNetworkRequest in replyFinished()

i have following problem:

I have a class Foo which encapsulates a web-api. the interface has following functions:

Foo::addItem( QString id )
Foo::updateItem( QString id )

both function initiate a QNetworkRequest with the same URL but the usage of the data is different. Therefore i need to know in slot function Foo::replyFinished( QNetworkReply *wf_reply ) from where the QNetworkRequest originated.

How would you solve this?

I could use variable to store the adress of the QNetworkRequest to compare it later to wf_reply->request() but this seems like a hack to me. Considering you can call addItem() or updateItem() hundred times before replyFinished() is executed for the first time. The best way would be to add a sting or integer to QNetworkRequest which contains the function name or id.

In your original QNetworkRequest you can set an attribute with

setAttribute(Attribute code, const QVariant & value)

Attribute is an enum and there is a reserved code for just this situation, QNetworkRequest::User . (See: Attribute )

In your QNetworkReply , you can pull the QNetworkRequest with request() then get the Attribute from there with attribute()

Bit of a hack, but I think it should work.

You have four options:

  1. Connect void QNetworkReply::finished() signal of each reply you create with one of your functions handling specific kind of requests
  2. Use setAttribute() in QNetworkRequest as suggested by Brian
  3. Use void QNetworkRequest::setOriginatingObject(QObject * object) which was added just for this purpose. The problem in your situation is that both kinds of your requests originate from the same QObject. You could create two dummy QObjects just for the purpose of sending their adresses to mark requests or you could use reinterpret_cast to convey kind of a request as a pointer.
  4. Keep track of initiated requests yourself as you suggested. Because there can be any number of requests active in one time you would have to use two lists of pointers (one for each kind of requests) for example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM