0

我正在尝试使用 QsignalMapper 在完成的信号上将我的字符串传递给 img_loaded 函数。但我无法得到任何结果,请帮助。

   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
}
4

3 回答 3

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
         .....
     }
 }
于 2015-06-10T07:59:51.800 回答
2

QSignalMapper在这种情况下您不能使用。QSignalMapper允许为每个发送者单独指定附加数据。但是,您只有一个发件人(QNetworkAccessManager对象)。您可以使用QNetworkReply's 信号(如@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
}
于 2014-01-26T11:11:09.327 回答
-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();
}
于 2014-01-25T19:44:36.310 回答