一、使用QSlider设计一个进度条,并让其通过线程自己动起来
程序代码:
<1> Widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QThread>
#include "mythread.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
myThread* thread;
public slots:
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
};
#endif // WIDGET_H
<2> Widget.cpp:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
thread = new myThread(this);//创建线程
QObject::connect(thread,&myThread::pupdate,ui->horizontalSlider,&QSlider::setValue);
QString qss = (R"(
QSlider {
background-color: transparent;
}
QSlider::groove:horizontal {
background-color: #E0E0E0;
height: 10px;
border-radius: 5px;
}
QSlider::sub-page:horizontal {
background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #6A11CB, stop:1 #2575FC);
border-radius: 5px;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.2);
}
QSlider::handle:horizontal {
background: #FFFFFF;
width: 16px;
height: 16px;
margin: -4px 0;
border-radius: 8px;
border: 2px solid #2575FC;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.2);
}
)");
ui->horizontalSlider->setStyleSheet(qss);
}
Widget::~Widget()
{
thread->terminate();
delete ui;
}
void Widget::on_pushButton_clicked()
{
thread->start();
}
void Widget::on_pushButton_2_clicked()
{
thread->terminate();
}
<3> myThread.h:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QSlider>
class myThread : public QThread
{
Q_OBJECT
public:
myThread(QObject* parent = nullptr);
protected:
virtual void run() override;
signals:
void pupdate(int progress);
private:
};
#endif // MYTHREAD_H
<4> myThread.cpp:
#include "mythread.h"
myThread::myThread(QObject* parent)
:QThread(parent)
{
}
void myThread::run()
{
int progress = 0;
while(1){
QThread::usleep(5000);
progress = (progress + 1) % 101;
emit pupdate(progress);
}
}
运行结果: