首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Qt多线程施用-QRunnable

2012-11-11 
Qt多线程应用--QRunnablehttp://blog.csdn.net/lefttime/article/details/5717349?作为Qt类中少有的基类,

Qt多线程应用--QRunnable

http://blog.csdn.net/lefttime/article/details/5717349

?

作为Qt类中少有的基类, QRunnable提供了简洁有效的可运行对象的创建.? 用QRunnable来创建独立的运行对象来运行 不涉及界面元素的数据处理过程 非常合适.

?

优点: 创建过程简洁, 使用方便, 配合着自身的autoDelete特性, 有点“招之即来, 挥之即去”的感觉.

缺点: 无法实时提供自身的运行状态.

?

举个处理过程中反馈进度的例子

Qt多线程施用-QRunnable

main.cpp

?

  • #include?<QApplication>??
  • #include?<QProgressBar>??
  • #include?<QThreadPool>??
  • ??
  • #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

    ?

  • #ifndef?RUNNABLEINST_H??
  • #define?RUNNABLEINST_H??
  • ??
  • #include?<QRunnable>??
  • ??
  • class?QProgressBar;??
  • class?runnableInst?:?public?QRunnable??
  • {??
  • public:??
  • ????runnableInst(QProgressBar*?progressBar);??
  • ????virtual?~runnableInst();??
  • ??
  • ????void?run();??
  • ??
  • private:??
  • ????QProgressBar*?m_ProgressBar;??
  • };??
  • ??
  • #endif?//?RUNNABLEINST_H??

    ?

    runnableInst.cpp

    ?

  • #include?"runnableInst.h"??
  • #include?<QTest>??
  • #include?<QProgressBar>??
  • ??
  • 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是比较危险的事!

  • 热点排行