Qt C ++下载XML文件并在textEdit中显示它

时间:2017-04-13 21:01:48

标签: c++ xml qt

从服务器下载XML文件时遇到问题。有一些代码:

QByteArray data;
...
void DownloadXML::on_pushButton_clicked()
{
     QUrl address = "abc.com/file.xml"

     QNetworkAccessManager *manager = new QNetworkAccessManager(this);
     connect(manager, SIGNAL(finished(QNetworkReply*)),
     this, SLOT(replyFinished(QNetworkReply*)));

     QNetworkRequest request;
     request.setUrl(address); 
     manager->get(request);

     ui->textEdit->insertPlainText(QString::fromAscii(data));
}

并回复完成插槽:

void DownloadXML::replyFinished(QNetworkReply *reply){
    reply->deleteLater();
    data = reply->readAll();
}

我的问题是:当我第一次点击按钮时,xml文件没有显示在textEdit中,但是当我第二次点击按钮时,xml文件正常显示。我怎么能解决这个问题?我认为我必须在程序中等待下载数据,但我不知道该怎么做。

顺便说一下。对不起我的英文

1 个答案:

答案 0 :(得分:0)

问题是在发出经理完成的信号之前调用ui->textEdit->insertPlainText(QString::fromAscii(data));。删除该行和

将您的广告位更改为:

void DownloadXML::replyFinished(QNetworkReply *reply){
    reply->deleteLater();
    data = reply->readAll();
    ui->textEdit->insertPlainText(QString::fromAscii(data));
}

或者,您可以使用QEventLoop等待信号被调用。

void DownloadXML::on_pushButton_clicked()
{
     QUrl address = "abc.com/file.xml"

     QNetworkAccessManager *manager = new QNetworkAccessManager(this);

     QNetworkRequest request;
     request.setUrl(address); 
     QNetworkReply *reply = manager->get(request);

     QEventLoop loop;
     connect(manager, SIGNAL(finished()), &loop, SLOT(quit()));
     loop.exec();

     if(reply->error() == QNetworkReply::NoError)
     {
         //No Error
         reply->deleteLater();
         data = reply->readAll();
         ui->textEdit->insertPlainText(QString::fromAscii(data));
     }
     loop.quit();
}