将代码示例添加到QT C ++

时间:2016-01-16 02:29:59

标签: c++ qt

我想在我的简单项目中添加一些QT示例代码。示例代码位于:https://wiki.qt.io/Download_Data_from_URL

它由filedownloader.cpp和filedownloader.h组成 - 此代码从提供的URL下载图形。

我已将这些文件添加到我的项目中并获得干净的编译。我想我理解代码好了(我主要是编码器,而不是c ++),但我不明白如何将我的项目创建的QUrl传递给filedownloader.cpp

"项目"只是一个简单的main.cpp / mainwindow.cpp / mainwindow.ui,它提供了一个按下的按钮。按下按钮调用以下例程:

void MainWindow::on_pushButton_clicked()
{
// pass to filedownloader to process
QUrl fileloc("http://www.test.com/test.jpg");
}

如何将QUrl fileloc提供给filedownload.cpp?

1 个答案:

答案 0 :(得分:1)

您必须向FileDownloader添加一个新方法,该方法接受QUrl并开始下载。

filedownloader.h:

#ifndef FILEDOWNLOADER_H
#define FILEDOWNLOADER_H

#include <QObject>
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

class FileDownloader : public QObject
{
 Q_OBJECT
 public:
  explicit FileDownloader(QUrl imageUrl, QObject *parent = 0);
  virtual ~FileDownloader();
  QByteArray downloadedData() const;

 signals:
  void downloaded();

 public slots:
  void download(QUrl url);   // <------ Here it is

 private slots:
  void fileDownloaded(QNetworkReply* pReply);

 private:
  QNetworkAccessManager m_WebCtrl;
  QByteArray m_DownloadedData;
};

#endif // FILEDOWNLOADER_H

filedownloader.cpp:

#include "filedownloader.h"

FileDownloader::FileDownloader(QObject *parent) :
 QObject(parent)
{
 connect(
  &m_WebCtrl, SIGNAL (finished(QNetworkReply*)),
  this, SLOT (fileDownloaded(QNetworkReply*))
  );
 // <------ Notice, that i've removed downloading code from here
}

FileDownloader::~FileDownloader() { }

void FileDownloader::fileDownloaded(QNetworkReply* pReply) {
 m_DownloadedData = pReply->readAll();
 //emit a signal
 pReply->deleteLater();
 emit downloaded();
}

void FileDownloader::download(QUrl url) { // <------ And its definition
 QNetworkRequest request(url);
 m_WebCtrl.get(request);
}

QByteArray FileDownloader::downloadedData() const {
 return m_DownloadedData;
}

然后您的on_pushButton_clicked将如下所示:

void MainWindow::on_pushButton_clicked()
{
// pass to filedownloader to process
QUrl fileloc("http://www.test.com/test.jpg");
m_filedownloader.download(fileloc);
}