Qt多线程应用--QRunnable

main.cpp

view plain
#include
#include
#include

#include “runnableInst.h”

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QProgressBar progressBar;  
progressBar.setValue(50);  
progressBar.show();  

runnableInst* hInst = new runnableInst(&progressBar);  
QThreadPool::globalInstance()->start(hInst);  

return app.exec();  

}

runnableInst.h

view plain
#ifndef RUNNABLEINST_H
#define RUNNABLEINST_H

#include

class QProgressBar;
class runnableInst : public QRunnable
{
public:
runnableInst(QProgressBar* progressBar);
virtual ~runnableInst();

void run();  

private:
QProgressBar* m_ProgressBar;
};

#endif // RUNNABLEINST_H

runnableInst.cpp

view plain
#include “runnableInst.h”
#include
#include

runnableInst::runnableInst(QProgressBar* progressBar)
QRunnable(), m_ProgressBar(progressBar)
{
}

runnableInst::~runnableInst()
{

}

void runnableInst::run()
{
for(int step = 1; step <= 100; step++)
{
// 处理数据过程
//…

    // 这两句只是测试用, 针对不同的环境可采用相应的进度反馈  
    QMetaObject::invokeMethod(m_ProgressBar, "setValue", Q_ARG(int, step));  
    QTest::qSleep(100);  

    //...  
}  

}

当QRunnable运行结束, 它自身会被销毁, 所以用不着担心内存泄露(除了指定设置setAutoDelete(false)); 不过要注意在数据或事件对象的处理~` 好比例子中QMetaObject::invokeMethod是比较危险的事!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值