Qt中多线程下载大文件
#pragma once
#include <QWidget>
#include <QPushButton>
#include "ThreadPool.h"
#include <QProgressBar>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = Q_NULLPTR);
private:
void initUI();
void initConnect();
private:
QPushButton* m_dlBtn;
DownLoad::ThreadPool threadPool;
QMap<QString ,std::pair<QLabel*,QProgressBar*> > controlMap;
};
#include "MainWindow.h"
#include "Task.h"
#include "ThreadPool.h"
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
initUI();
initConnect();
}
void MainWindow::initUI()
{
m_dlBtn = new QPushButton(this);
m_dlBtn->setText(QString("DownLoad"));
QVBoxLayout* layout = new QVBoxLayout();
layout->setSpacing(10);
layout->setContentsMargins(10, 10, 10, 10);
layout->addWidget(m_dlBtn);
for (int i = 0; i < 10; i++)
{
DownLoad::Task* task = new DownLoad::Task("http://mirrors.tuna.tsinghua.edu.cn/archlinux/iso/2023.12.01/archlinux-2023.12.01-x86_64.iso", QString("C:/Users/gd09861-hlw/Desktop/11111/archlinux-2023.12.01-x86_64_%1.iso").arg(i), DownLoad::Task::WorkModel::DOWNLOAD);
threadPool.push(task);
QLabel *label = new QLabel(this);
label->setText(QString("%1").arg(i));
QProgressBar *progressBar = new QProgressBar(this);
controlMap.insert(task->id(), std::make_pair(label, progressBar));
QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->addWidget(label);
hLayout->addWidget(progressBar);
layout->addLayout(hLayout);
}
this->setLayout(layout);
}
void MainWindow::initConnect()
{
connect(m_dlBtn, &QPushButton::clicked, [&]() {
threadPool.startAll();
}
);
connect(&threadPool, &DownLoad::ThreadPool::sigUpdateTaskProgress, this, [&](QString id, qint64 bytesR, qint64 bytesT) {
controlMap[id].second->setValue((bytesR*100.0f) / (bytesT*1.0f));
});
connect(&threadPool, &DownLoad::ThreadPool::sigUpdateTaskState, this, [&](QString id,DownLoad::Task::