使用QNetWorkAccessManager将值传递给插槽

时间:2014-01-25 18:58:19

标签: qt qt-signals

我正在尝试使用QsignalMapper将我的String传递给img_loaded函数,在完成的SIGNAL上。但我无法得到任何结果,请帮忙。

   QString mystring = "value";
   QNetworkAccessManager *m_netwManager = new QNetworkAccessManager(this);
   QUrl url("http://images.gs-cdn.net/static/albums/80_9299765.jpg");
   QNetworkRequest request(url);
   connect(m_netwManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(img_loaded(QNetworkReply*)));

void MainWindow::img_loaded(QNetworkReply *rep){
   //Handle my String here
}

3 个答案:

答案 0 :(得分:5)

如果您想提供其他参数来识别networkReply,请尝试以下方法:

void myClass::downloadMedia(QString url, int mediaType, int messageID)
{
    bool connect_result;
    QNetworkAccessManager *manager2 = new QNetworkAccessManager(this);
    connect_result = connect(manager2, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(onMediaDownloaded(QNetworkReply*)));
    Q_ASSERT(connect_result);

    QNetworkReply* reply = manager2->get(QNetworkRequest(url));
// Here are the additional parameters
    reply->setProperty("mediaType", mediaType);
    reply->setProperty("messageID", messageID);
}

还有插槽

void myClass::onMediaDownloaded(QNetworkReply *reply)
 {
     int mediaType = reply->property("mediaType").toInt();
     int messageID = reply->property("messageID").toInt();
     switch (mediaType) {
         // Handle different media types
         .....
     }
 }

答案 1 :(得分:2)

在这种情况下,您无法使用QSignalMapperQSignalMapper允许为每个发件人分别指定其他数据。但是,您只有一个发件人(QNetworkAccessManager对象)。您可以使用QNetworkReply的信号(如@derkode建议的那样)并使用QSignalMapper,但这是一个过度复杂的问题。

QNetworkAccessManager已将QNetworkReply*个对象作为信号参数发送。这与QSignalMapper功能非常相似。我们只需要为每个回复附加额外的数据。例如,您可以在班级中创建此类私人字段:

QHash<QNetworkReply*, QString> data_storage;

QString替换为附加数据的类型(QVariant,int或其他)。提出请求时添加数据:

QNetworkReply* reply = m_netwManager->get(...);
data_storage[reply] = my_data;

在请求完成并清理时获取该数据:

void MainWindow::img_loaded(QNetworkReply *reply) {
  QString my_data = data_storage[reply];
  data_storage.remove(reply);
  //... read reply and use data
}

答案 2 :(得分:-1)

尝试:

QString mystring = "value";
QNetworkRequest request;
request.setUrl(QUrl("http://images.gs-cdn.net/static/albums/80_9299765.jpg");

QNetworkAccessManager m_networkManager = new QNetworkAccessManager(this);
QNetworkReply *reply = m_networkManager->get(request);

connect(reply, SIGNAL(finished()), this, SLOT(img_loaded()));


void MainWindow::img_loaded() {
   //For example
   QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
   QByteArray data = reply->readAll();
}