Qt中多线程使用案列

发布时间:2023年12月21日

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::
文章来源:https://blog.csdn.net/weixin_42252757/article/details/135115538
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。