基于http://blog.csdn.net/liang19890820/article/details/52186626修改
适用于像我这样的小白,目的就是实现点击开始按钮,进度条值从0++到100
添加线程类:
不知道是什么原因,我添加QThread的C++ class总是不成功,我拷贝了以前同事建立的项目下面的thread_receive.h与thread_receive.cpp文件,然后手动添加在项目中。
1
在mainwindow.h头文件中,定义了一个thread_receive类;在mainwindow.cpp源文件中实例化:
thread_reflash = new thread_receive(this);
startThread_slot()函数:
void MainWindow::startTheard_slot()
{
thread_refresh->start();
}
connect了pStartButton与startThread_slot()
connect(ui->pStartButton, SIGNAL(clicked()), this, SLOT(startThread_slot()));
先编译一下,看有没有报错,然后点击一下按钮,看有没有qDebug信息输出
2
接下来要编写thread_receive里面的run()函数了
run() 函数实现的功能是间隔50ms将value值+1,并emit出去
这里定义了一个指向MainWindows的指针pt,因为我的value值,resultReady()函数都在MainWindows的构造函数中定义的
void thread_receive:: run()
{
MainWindow *pt = (MainWindow*)parent();
qDebug() << "Worker Run Thread : " << QThread::currentThreadId();
while (pt->value < 100)
{
msleep(50);
pt->value++;
qDebug() << pt->value;
emit pt->resultReady(pt->value);
}
qDebug() << "end thread!" << endl;
}
3
在MainWindows中,connect了resultReady信号到show_slot()槽函数,show_slot()槽函数实现进度条m_pProgressBar值的变化
connect(this, SIGNAL(resultReady(int)), this, SLOT(show_slot()));
void MainWindow::show_slot()
{
ui->m_pProgressBar->setValue(value);
qDebug() << value;
}