mythread.h
cpp
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class myThread : public QThread
{
Q_OBJECT
public:
myThread(QObject* parent=nullptr);
protected:
virtual void run() override;
signals:
void readSig();
};
#endif // MYTHREAD_H
mythread.cpp
cpp
#include "mythread.h"
myThread::myThread(QObject* parent):QThread(parent){}
void myThread::run()
{
while(1){
emit readSig();
QThread::msleep(10);
}
}
myFile类
cpp
#include "myfile.h"
myFile::myFile()
{
}
myFile::myFile(const QString &name):QFile(name){}
void myFile::setFilename(const QString &filename)
{
this->rename(filename);
}
自定义主窗口要实现的功能
cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
t = new myThread(this);//定义线程
//qss指令的编写
QString qss = "QSlider{border:2px solid;}"
"QSlider::sub-page:horizontal { background-color: green; }"
"QSlider::groove:horizontal { background-color: gray; }";
//自定义进度条样式
ui->horizontalSlider->setStyleSheet(qss);
//等待接收trigger信号,当接受到trigger信号触发槽函数startSlot;
QObject::connect(this,&Widget::trigger,this,&Widget::startSlot);//链接触发读取信号(触发t->start())
//等待接收线程myThread中的readSig信号,当接受到readSig信号触发槽函数:readSlot;
QObject::connect(t,&myThread::readSig,this,&Widget::readSlot);//链接线程读取信号和Widget槽函数
}
Widget::~Widget()
{
t->terminate();
delete ui;
}
void Widget::on_pushButton_clicked()
{
//点击按钮就打开文件对话框
QString fileName =QFileDialog::getOpenFileName(this,"打开文件","D:/pic","Text Files (*.*);;All Files (*)");
if(fileName.isEmpty()){
return;
}else{
emit trigger();//发送下载信号
fd = new QFile(fileName);//QFile设置文件名
fd->open(QIODevice::ReadOnly);//QFile打开文件
//将进度条的范围设置为文件的大小
ui->horizontalSlider->setRange(0,fd->size());//将进度条的范围设置为文件的大小
}
}
void Widget::startSlot()//启动线程,线程执行每隔10秒发送readSig信号
{
t->start();
}
void Widget::readSlot()
{
btarr=fd->read(maxsize);//一次读取maxsize字节(读取速度)
size+=maxsize;
ui->horizontalSlider->setValue(size);//读取多少进度条增长多少
if(size>=fd->size()){
qDebug() << "读取完毕";
fd->close();//关闭文件指针
size=0;
t->terminate();//关闭线程
}
}
主窗口类的私有成员变量
cpp
private:
Ui::Widget *ui;
QFile* fd;
QByteArray btarr;
qint64 maxsize=1024;
myThread* t;
qint64 size=0;
主窗口类的成员信号
cpp
signals:
void trigger();
主窗口类的成员方法-----槽函数
cpp
public slots:
void readSlot();
void startSlot();