使用QT的文件IO QFile 和 QFileDialog文件对话框,读取一个选中的文件,然后使用QSlider显示读取的进度,QSlider需要改成进度条的样式
widget.cpp
cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->horizontalSlider->setRange(0,100);
QString qss="QSlider::sub-page:horizontal{background-color:rgb(0,255,0,255)}QSlider::groove::horizontal{background-color:gray}";
ui->horizontalSlider->setStyleSheet(qss);
timer=new QTimer(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::readData(const QString &filename)
{
file_src.setFileName(filename);
file_src.open(QIODevice::ReadOnly);
if(file_src.exists()==false){
qDebug() << "文件不存在";
return ;
}
if(data.size()>=file_src.size()){
i=0;
ui->horizontalSlider->setValue(i);
timer->stop();
return ;
}
QByteArray temp=file_src.read(100);
data+=temp;
i=static_cast<int>(static_cast<double>(data.size())/file_src.size()*100);
qDebug() << i;
ui->horizontalSlider->setValue(i);
qDebug() << data.size();
//QString str=QString::fromLocal8Bit(arr);
file_src.close();
}
void Widget::writeData(const QString &filename, const QByteArray &data)
{
file_des.setFileName(filename);
file_des.open(QIODevice::WriteOnly);
//QByteArray arr=data.toLocal8Bit();
file_des.write(data);
file_des.close();
qDebug() << "文件保存成功";
}
void Widget::on_pushButton_clicked()
{
path_src=QFileDialog::getOpenFileName(this,"打开文件","C:/Users/pzctj/Desktop/qtimage","Images (*.png *.xpm *.jpg *.bmp);;Text files (*.txt);;All files (*.*)");
//qDebug() << str;
timer->start(100);
QObject::connect(timer,&QTimer::timeout,this,&Widget::ontimeOut);
}
void Widget::on_pushButton_2_clicked()
{
path_des=QFileDialog::getSaveFileName(this,"保存文件","C:/Users/pzctj/Desktop/qtimage","Images (*.png *.xpm *.jpg *.bmp);;Text files (*.txt);;All files (*.*)");
qDebug() << path_des;
}
void Widget::ontimeOut()
{
readData(path_src);
}
widget.h
cpp
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QFileDialog>
#include <QDebug>
#include <QFile>
#include <synchapi.h>
#include <cstdlib>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void readData(const QString& filename);
void writeData(const QString& filename,const QByteArray& data);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
public slots:
void ontimeOut();
private:
Ui::Widget *ui;
QFile file_src;//用于读取文件
QFile file_des;//用于写文件
QByteArray data;//用于暂时接收文件内容
int i=0;//用于记录进度条
QTimer* timer;
QString path_src;
QString path_des;
};
#endif // WIDGET_H