3

您好,我编写了应该下载网页并将其保存为文件的程序。它做到了,但只是部分做到了。有没有人遇到过这样的问题?

mainwindow.cpp 源文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QNetworkAccessManager>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    netManager = new QNetworkAccessManager;
    setFile("myPage");
}

MainWindow::~MainWindow()
{
    netManager->deleteLater();
    delete ui;
}

void MainWindow::setFile(QString fileURL)
{
    QString savePath;

    savePath = QString("D:/page.html");

    QNetworkRequest request;
    request.setUrl(QUrl(fileURL));
    reply = netManager->get(request);

    file = new QFile;
    file->setFileName(savePath);
    file->open(QIODevice::WriteOnly);

    connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onProgress(qint64,qint64)));
    connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
    connect(reply, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));
}

void MainWindow::onProgress(qint64 bRead, qint64 bTotal)
{
    qDebug(QString::number(bRead).toLatin1() + " - " + QString::number(bTotal).toLatin1());
}

void MainWindow::onFinished(QNetworkReply *reply)
{
    switch (reply->error())
    {
    case QNetworkReply::NoError:
    {
        qDebug("File downloaded");
        qDebug() << file->size();
    }break;
    default:
    {
        qDebug(reply->errorString().toLatin1());
    }
    }
    if(file->isOpen())
    {
        file->close();
        file->deleteLater();
    }
}

void MainWindow::onReadyRead()
{
    file->write(reply->readAll());
}

void MainWindow::onReplyFinished()
{
    if(file->isOpen())
    {
        file->close();
        file->deleteLater();
    }
}

mainwindow.h 头文件源文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QFile>
#include <QNetworkReply>
#include <QNetworkReply>
#include <QStringList>

namespace Ui
{
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void setFile(QString fileURL);
private slots:
    void onFinished(QNetworkReply *);
    void onProgress(qint64 bRead, qint64 bTotal);
    void onReadyRead();
    void onReplyFinished();
private:
    Ui::MainWindow *ui;
    QNetworkAccessManager *netManager;
    QNetworkReply *reply;
    QFile *file;
};

#endif // MAINWINDOW_H

我试图自己解决它,但经过多次尝试我失败了。我是 QT 的初学者,所以我可能在某个地方犯了一个错误,我什至没有看到它。任何人都可以带我找到解决问题的正确方法吗?

4

1 回答 1

1

你应该把这个:

connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));

前:

reply = netManager->get(request);

修改后工作正常;)

于 2013-06-03T19:29:31.460 回答