案例需求:利用QT线程操作,实现拷贝复制文件操作
代码:
myfile.h
#ifndef MYFILE_H
#define MYFILE_H
#include <QObject>
#include <QDebug>
#include <QThread>
#include <QFile>
#include <QtWidgets>
class MyFile : public QObject
{
Q_OBJECT
public:
explicit MyFile(QObject *parent = nullptr);
void thread_file(QString path);
signals:
void my_signal(); // 失败信号
void success_signal(); // 成功信号
public slots:
};
#endif // MYFILE_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QDebug>
#include <QThread>
#include "myfile.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButton_clicked();
signals:
void sendsignal(QString path);
private:
Ui::Widget *ui;
QThread *thread;
MyFile *file;
};
#endif // WIDGET_H
myfile.cpp
#include "myfile.h"
MyFile::MyFile(QObject *parent) : QObject(parent)
{
}
void MyFile::thread_file(QString path)
{
if(path.isEmpty()){
qDebug()<<"取消选择"<<endl;
emit my_signal();
return ;
}
else{
qDebug()<<path<<endl;
QFile file(path);
if(!file.open(QIODevice::ReadOnly)){
qDebug()<<"读取失败";
emit my_signal();
return ;
}
QString writepath = "./writefile.cpp";
QFile writefile(writepath);
if(!writefile.open(QIODevice::WriteOnly|QIODevice::Truncate)){
qDebug()<<"新建失败";
emit my_signal();
return ;
}
while(!file.atEnd()){ // 拷贝
QByteArray buf;
file.read(1024);
writefile.write(buf);
}
// 关闭文件
file.close();
writefile.close();
emit success_signal();
}
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QThread>
#include "myfile.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
thread = new QThread(this);
file = new MyFile;
file->moveToThread(thread);
//connect(thread,&QThread::started,file,&MyFile::thread_file);
connect(this,&Widget::destroyed,this,[=](){
thread->quit();
thread->wait();
});
connect(file,&MyFile::my_signal,this,[=](){ // 只能在主线程对界面进行操作
this->ui->label->setText("COPY失败");
});
connect(file,&MyFile::success_signal,this,[=](){
this->ui->label->setText("COPY完成");
});
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
QString path = QFileDialog::getOpenFileName(this,tr("打开文件"),"./","Text filex(*.cpp)");
connect(this,&Widget::sendsignal,file,&MyFile::thread_file);
emit sendsignal(path);
this->ui->label->setText("开始拷贝");
thread->start();
}
ui