1:是进度条通过线程自己动起来
thread.h
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
class Thread : public QThread
{
Q_OBJECT
public:
Thread(QObject *parent = nullptr);
void setMax(int value);
signals:
void valueChanged(int value);
protected:
void run() override;
private:
int currentValue;
int max;
};
#endif // THREAD_H
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSlider>
#include <QVBoxLayout>
#include "thread.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void updateSlider(int value);
private:
QSlider *slider;
Thread *thread; // 使用 Thread 类
};
#endif // WIDGET_H
thread.cpp
#include "thread.h"
Thread::Thread(QObject *parent)
: QThread(parent), currentValue(0), max(100)
{
}
void Thread::setMax(int value)
{
max = value;
}
void Thread::run()
{
while (currentValue <= max && !isInterruptionRequested())
{
currentValue++;
emit valueChanged(currentValue);
msleep(100);
}
}
widget.cpp
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
// 创建滑块
slider = new QSlider(Qt::Horizontal, this);
slider->setRange(0, 100); // 设置滑块范围
slider->setValue(0); // 初始值为0
// 设置QSS样式
slider->setStyleSheet(
"QSlider::groove:horizontal {"
"background: #444; height: 4px; border-radius: 2px;}"
"QSlider::handle:horizontal {"
"background: #ff0000; width: 10px; border-radius: 5px;}"
"QSlider::sub-page:horizontal {"
"background: #00ff00; border-radius: 2px;}");
// 创建布局并添加滑块
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(slider);
setLayout(layout);
// 初始化工作线程
thread = new Thread(this);
connect(thread, &Thread::valueChanged, this, &Widget::updateSlider);
thread->setMax(slider->maximum());
thread->start(); // 启动线程
}
Widget::~Widget()
{
thread->requestInterruption(); // 请求中断线程
thread->wait(); // 等待线程结束
delete thread;
}
void Widget::updateSlider(int value)
{
slider->setValue(value); // 更新滑块值
}