mythread循环给主线程发送信号实现主线程循环的功能
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QFile>
#include <QFileDialog>
#include <QTextStream>
#include <QByteArray>
#include "mythread.h"QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_pushButton_clicked();void slider_move();private:QFile* fp;mythread* t;int i=0;Ui::Widget *ui;
};
#endif // WIDGET_H
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H#include <QThread>class mythread : public QThread
{Q_OBJECT
public:mythread(QObject *parent = nullptr);
signals:void sndsig();
protected:virtual void run() override;};#endif // MYTHREAD_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);fp = new QFile(this);t = new mythread(this);QObject::connect(t,&mythread::sndsig,this,&Widget::slider_move);QString qss = "QSlider::sub-page{background-color:rgba(0, 255, 0, 100)} QSlider::groove{background-color:lightGray}";ui->hsl->setStyleSheet(qss);
}Widget::~Widget()
{t->terminate();delete ui;
}void Widget::on_pushButton_clicked()
{QString file = QFileDialog::getOpenFileName(this,"閫夋嫨鏂囦欢");fp->setFileName(file);fp->open(QIODevice::ReadOnly);t->start();
}void Widget::slider_move()
{int len = fp->size();QByteArray text = fp->read(1024);QString txt = QString::fromLocal8Bit(text);ui->lineEdit->setText(txt);ui->hsl->setRange(0,len);ui->hsl->setValue(i+=1024);if(fp->atEnd() == true){fp->close();t->terminate();}
}
mythred.cpp
#include "mythread.h"mythread::mythread(QObject *parent):QThread(parent)
{}void mythread::run()
{while (1) {emit sndsig();QThread::msleep(100);}}