一、widget.h
#ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QMenuBar> #include <QFileDialog> #include <QFile> #include <QDebug> #include <QTimer> QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACEclass Widget : public QWidget {Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget(); signals://void sendName(QString& filename); public slots:void openFile();//void readFile(QString& filename);void recvFile(); private:Ui::Widget *ui;QMenuBar* bar;QAction* open_action;QFileDialog* file;QFile open_file;QTimer* timer;QString string;int i = 0;qint64 size = 0;}; #endif // WIDGET_H
二、widget.cpp
#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);bar = new QMenuBar(this);QMenu* m1 = bar->addMenu("文件(F)");open_action = m1->addAction("打开");QObject::connect(open_action,&QAction::triggered,this,&Widget::openFile);//QObject::connect(this,&Widget::sendName,this,&Widget::readFile);timer = new QTimer(this);QObject::connect(timer,&QTimer::timeout,this,&Widget::recvFile);QString qss = "QSlider::sub-page{background-color:green} QSlider::groove{background-color:lightGray}";ui->horizontalSlider->setStyleSheet(qss); }Widget::~Widget() {delete ui; }void Widget::openFile() {QString filename =file->getOpenFileName(this,"打开文件","D:/QQ","text(*.doc *.docx *.pdf *.txt)");//emit sendName(filename);qDebug() << filename;open_file.setFileName(filename);open_file.open(QFile::ReadOnly);timer->start(100);if(open_file.exists() == false){qDebug() << "文件不存在";return;}size = open_file.size();ui->horizontalSlider->setRange(0,size); }void Widget::recvFile() {QByteArray arr = open_file.read(1024);QString str = QString::fromLocal8Bit(arr);qDebug() << str;ui->horizontalSlider->setValue(i+=1024);string += str;ui->textEdit->setText(string);if(open_file.atEnd() == true){qDebug() << "文件读取完毕";open_file.close();timer->stop();} }
三、运行结果: