Qt下载图片|返回空字节数组

时间:2016-07-14 18:37:19

标签: c++ qt

我有一个程序可以访问选定的Imgur相册,获取照片列表,然后下载它们。一切顺利,我可以获得URL,但是当它下载它们时它们是空的。非常感谢任何帮助!

Main.cpp的:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    QList<QUrl> imageUrls;
    QNetworkAccessManager manager;
    QNetworkReply *response = manager.get(QNetworkRequest(QUrl("http://imgur.com/a/pthXN")));
    QEventLoop event;
    QObject::connect(response,SIGNAL(finished()),&event,SLOT(quit()));
    event.exec();
    QByteArray data = response->readAll();
    QWebView *view = new QWebView;
    view->setHtml(QString::fromUtf8(data));
    QWebElementCollection colls = view->page()->mainFrame()->findAllElements("div.post-image-container a");
    foreach(QWebElement elemento, colls)
    {
        imageUrls << elemento.attribute("href");
    }
    if (!QDir(QDir::homePath() + "/Documents/imgurvaca/").exists())
    {
        QDir().mkdir(QDir::homePath() + "/Documents/imgurvaca/");
    }
    QNetworkAccessManager *manager2 = new QNetworkAccessManager;
    QEventLoop eventLoop;
    QObject::connect(manager2, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    for (int x = 0; x < imageUrls.count(); x++)
    {
        QNetworkRequest request;
        request.setUrl(QUrl(imageUrls[x]).toString().remove("//"));

        QNetworkReply *pictureReply = manager2->get(request);

        qDebug() << QUrl(imageUrls[x]).toString().remove("//");//produces the url

        qDebug() << pictureReply->readAll();//returns "" empty

    }
    eventLoop.exec();
    w.show();

    return a.exec();
}

MainWindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

QList<QUrl> imageUrls;
int xval = 0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QPixmap bkgnd(":/images/background.jpg");
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);

    QPixmap leftBkgnd(":/images/leftArrow.png");
    QIcon leftIcon(leftBkgnd);
    ui->pushButtonLeft->setIcon(leftIcon);
    ui->pushButtonLeft->setIconSize(QSize(150, 150));

    QPixmap rightBkgnd(":/images/rightArrow.png");
    QIcon rightIcon(rightBkgnd);
    ui->pushButtonRight->setIcon(rightIcon);
    ui->pushButtonRight->setIconSize(QSize(150, 150));
    ui->pushButtonLeft->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
    QPixmap bkgnd(":/images/background.jpg");
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);
}

0 个答案:

没有答案