1:使用QT的文件IO QFile 和 QFileDialog文件对话框,读取一个选中的文件,然后使用QSlider显示读取的进度,QSlider需要改成进度条的样式
mythread.h
cpp
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QObject>
class mythread : public QThread
{
Q_OBJECT
public:
mythread(QObject *parent = Q_NULLPTR);
protected:
virtual void run() override;
signals:
void sndSig();
};
#endif // MYTHREAD_H
mthread.cpp
cpp
#include "mythread.h"
mythread::mythread(QObject *parent)
:QThread(parent)
{
}
void mythread::run()
{
while (1) {
emit sndSig();
this->msleep(50);
}
}
widget.h
cpp
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QComboBox>
#include <QSlider>
#include <QString>
#include <QTimer>
#include "mythread.h"
#include <QFileDialog>
#include <QDebug>
#include <QProgressBar>
#include <QMessageBox>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void readslot();
void startslot();
private slots:
void on_pushButton_clicked();
signals:
void trigger();
private:
Ui::Widget *ui;
QTimer* timer;
int i = 0;
mythread* t;
QFile* fd;
QByteArray btarr;
qint64 maxsize=1024;
qint64 size=0;
void readFileInChunks(const QString &content);
};
#endif // WIDGET_H
widget.cpp
cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->slider->setRange(1,100);
//设置按钮
QString qss = "QPushButton{background-color:black;color:red}QPushButton:hover{background-color:green}";
ui->pushButton->setStyleSheet(qss);
//设置下拉栏
QString qss1 = "QComboBox::drop-down{image:url(C:/Users/11214/Desktop/mn.jpg)}";
ui->comboBox->setStyleSheet(qss1);
//设置滑动条
QString qss2 = "QSlider::sub-page:horizontal{background-color:rgb(0,255,0)}\
QSlider::groove:horizontal{background-color:lightgray}";
ui->slider->setStyleSheet(qss2);
//创建线程
t = new mythread(this);
QObject::connect(t,&mythread::sndSig,this,&Widget::readslot);
QObject::connect(this,&Widget::trigger,this,&Widget::startslot);
}
Widget::~Widget()
{
t->terminate();
delete ui;
}
//点击按钮触发文件对话框
void Widget::on_pushButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this,"打开文件","D:/qt.img","Text Files (*.*);;All Files (*)");
if(fileName.isEmpty()){
return;
}else{
emit trigger();
//QFile设置文件名
fd = new QFile(fileName);
//打开文件
fd->open(QIODevice::ReadOnly);
//将进度条的范围设置为文件的大小
ui->slider->setRange(0,fd->size());
}
}
void Widget::startslot()
{
t->start();
}
void Widget::readslot()
{
btarr = fd->read(maxsize);
size += maxsize;
//进度条随读取增长
ui->slider->setValue(size);
if(size >= fd->size()){
qDebug() << "读取完毕";
fd->close();
size = 0;
//关闭线程
t->terminate();
}