gpt4 book ai didi

c++ - 我如何在 Qt 中从 Internet 下载文件?

转载 作者:太空狗 更新时间:2023-10-29 21:06:20 25 4
gpt4 key购买 nike

我不知道是什么问题...编译器 (Qt) 运行程序没有错误,但文件未下载...你能告诉我哪里出了问题吗?

我通过示例“下载”制作,它位于 qt 文件夹中。唯一的区别是他们有一个控制台,而我有 Windows 应用程序。

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtNetwork>
#include <QMainWindow>

namespace Ui {

class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private slots:
void on_pushButton_clicked();

private:
Ui::MainWindow *ui;
};

class DownloadManager: public QObject
{
Q_OBJECT
QNetworkAccessManager manager;
QList<QNetworkReply *> currentDownloads;

public:
DownloadManager();
void doDownload(const QUrl &url);
QString saveFileName(const QUrl &url);
bool saveToDisk(const QString &filename, QIODevice *data);

public slots:
void execute();
void downloadFinished(QNetworkReply *reply);
};


#endif // MAINWINDOW_H

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtNetwork>
#include <QNetworkAccessManager>
#include <QStringList>
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStringList>
#include <QTimer>
#include <QUrl>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
#if defined(Q_WS_S60)
w.showMaximized();
#else
w.show();
#endif

return a.exec();
}

DownloadManager::DownloadManager()
{
connect(&manager, SIGNAL(finished(QNetworkReply*)),
SLOT(downloadFinished(QNetworkReply*)));
}

void DownloadManager::doDownload(const QUrl &url)
{
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);

currentDownloads.append(reply);
}

QString DownloadManager::saveFileName(const QUrl &url)
{
QString path = url.path();
QString basename = QFileInfo(path).fileName();

if (basename.isEmpty())
basename = "download";

if (QFile::exists(basename)) {
// already exists, don't overwrite
int i = 0;
basename += '.';
while (QFile::exists(basename + QString::number(i)))
++i;

basename += QString::number(i);
}

return basename;
}

bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
fprintf(stderr, "Could not open %s for writing: %s\n",
qPrintable(filename),
qPrintable(file.errorString()));
return false;
}

file.write(data->readAll());
file.close();

return true;
}

void DownloadManager::execute()
{
QStringList args = QCoreApplication::instance()->arguments();
args[0]="http://www.google.ru/images/srpr/logo3w.png";

QString arg=args[0];

QUrl url = QUrl::fromEncoded(arg.toLocal8Bit());
doDownload(url);

}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
QUrl url = reply->url();
if (reply->error()) {
fprintf(stderr, "Download of %s failed: %s\n",
url.toEncoded().constData(),
qPrintable(reply->errorString()));
} else {
QString filename = saveFileName(url);
if (saveToDisk(filename, reply))
printf("Download of %s succeded (saved to %s)\n",
url.toEncoded().constData(), qPrintable(filename));
}

currentDownloads.removeAll(reply);
reply->deleteLater();

if (currentDownloads.isEmpty())
// all downloads finished
QCoreApplication::instance()->quit();
}

主窗口.cpp

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


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}

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


void MainWindow::on_pushButton_clicked()
{
DownloadManager manager;

manager.execute();
QTimer::singleShot(0, &manager, SLOT(execute()));
}

最佳答案

问题出在你的代码上:

void MainWindow::on_pushButton_clicked()
{
DownloadManager manager;
manager.execute();
}

QNetworkAccessManager 是异步的,因此它需要一个事件循环来进行任何下载。但是当函数 on_pushButton_clicked() 返回并将控制权交还给事件循环时,QNetworkAccessManager 已经被销毁,没有时间做任何事情。

当您在 DownloadManager::execute 中添加一个 QMessageBox 时,您实际上正在运行另一个带有插槽 on_pushButton_clicked() 的事件循环,它为 QNetworkAccessManager 提供了执行其工作的机会。

正确的解决方案是动态分配 DownloadManager,并最终使其在完成所有下载后自行销毁。

void MainWindow::on_pushButton_clicked()
{
DownloadManager *manager = new DownloadManager(this);
manager->execute();
}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
...
if (currentDownloads.isEmpty())
this->deleteLater();
}

关于c++ - 我如何在 Qt 中从 Internet 下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7870017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com