【转】Qt多线程操作界面---在QThread更新QProgressBar

深藏阁楼爱情的钟 2021-12-16 10:53 717阅读 0赞

复制代码

  1. #include <QApplication>
  2. #include <QThread>
  3. #include <QMainWindow>
  4. #include <QProgressBar>
  5. #include <QPushButton>
  6. class RenderThread : public QThread
  7. {
  8. Q_OBJECT
  9. signals:
  10. void notify(int);
  11. public:
  12. RenderThread(QObject *parent = 0): QThread(parent)
  13. {
  14. };
  15. void test()
  16. {
  17. start(HighestPriority);
  18. };
  19. protected:
  20. void run()
  21. {
  22. int i =0;
  23. while (i<101)
  24. {
  25. msleep(50);
  26. i++;
  27. emit notify(i);
  28. }
  29. };
  30. };
  31. class MainWindow : public QMainWindow
  32. {
  33. Q_OBJECT
  34. public:
  35. MainWindow(QWidget *parent = 0)
  36. {
  37. resize(600, 400);
  38. centralWidget = new QWidget(this);
  39. progressBar = new QProgressBar(centralWidget);
  40. progressBar->setGeometry(QRect(130, 180, 321, 23));
  41. progressBar->setValue(0);
  42. pushButton = new QPushButton("test",centralWidget);
  43. pushButton->setGeometry(QRect(110, 100, 75, 23));
  44. QObject::connect(pushButton, SIGNAL(clicked()), this, SLOT(OnClicked()));
  45. this->setCentralWidget(centralWidget);
  46. };
  47. ~MainWindow(){};
  48. private:
  49. QProgressBar *progressBar;
  50. QPushButton *pushButton;
  51. QWidget *centralWidget;
  52. RenderThread render;
  53. public slots:
  54. void OnClicked()
  55. {
  56. connect(&render,SIGNAL(notify(int)),this,SLOT(OnNotify(int)));
  57. render.test();
  58. };
  59. void OnNotify(int i)
  60. {
  61. progressBar->setValue(i);
  62. };
  63. };
  64. #include "test.moc"
  65. int main(int argc,char* argv[])
  66. {
  67. QApplication app(argc,argv);
  68. MainWindow window;
  69. window.show();
  70. return app.exec();
  71. }

复制代码

http://blog.csdn.net/tingsking18/article/details/5096172

转载于:https://www.cnblogs.com/tiandsp/p/7580577.html

发表评论

表情:
评论列表 (有 0 条评论,717人围观)

还没有评论,来说两句吧...

相关阅读

    相关 QT QThread

    QThread类提供了一种独立于平台的方式来管理线程。 A.QThreads开始在run()中执行。默认情况下,run()通过调用exec()启动事件循环,并在线程内运行Q

    相关 QThread线编程分析

    QThread多线程编程分析 传统图形界面应用程序都只有一个线程执行,并且一次执行一个操作。如果用户调用一个比较耗时的操作,就会冻结界面响应。一个解决方法是按照事件处理的