温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Qt多线程程序设计中,可使用信号和槽进行线程通信

发布时间:2020-07-13 19:09:31 来源:网络 阅读:887 作者:WZM3558862 栏目:开发技术

Qt多线程程序设计中,可使用信号和槽进行线程通信。下面是一个简单的示例。

该程序实现了线程中自定义一个信号和槽,定时1秒发送信号,槽响应后打印一条信息。

[cpp] view plain copy Qt多线程程序设计中,可使用信号和槽进行线程通信Qt多线程程序设计中,可使用信号和槽进行线程通信

  1. #include <QtCore/QCoreApplication>  

  2. #include <QThread>  

  3. #include <stdio.h>  

  4. class MyThread:public QThread  

  5. {  

  6.     Q_OBJECT  

  7. public:  

  8.     MyThread();  

  9.     void stop();  

  10. private:  

  11.     bool isRunning;  

  12.     void run();  

  13. public slots:  

  14.     void showMsg();  

  15. signals:  

  16.     void msg();  

  17. };  

  18. MyThread::MyThread()  

  19. {  

  20.     isRunning = true;  

  21.     connect(this,SIGNAL(msg()),this,SLOT(showMsg()),Qt::DirectConnection);  

  22. }  

  23. void MyThread::showMsg()  

  24. {  

  25.     printf("Hello!\n");  

  26. }  

  27. void MyThread::run()  

  28. {  

  29.     while(isRunning)  

  30.     {  

  31.         sleep(1);  

  32.         emit msg();  

  33.     }  

  34.     printf("Exit!\n");  

  35. }  

  36. void MyThread::stop()  

  37. {  

  38.     isRunning = false;  

  39. }  

  40. int main(int argc, char *argv[])  

  41. {  

  42.     QCoreApplication a(argc, argv);  

  43.     MyThread mThread;  

  44.     mThread.start();  

  45.   

  46.     while(1)  

  47.     {  

  48.         if(getchar()=='B')  

  49.         {  

  50.             mThread.stop();  

  51.             mThread.wait();  

  52.             break;  

  53.         }  

  54.     }  

  55.     return a.exec();  

  56. }  

  57. #include "main.moc"  


在Qt Creator中编译时,需先使用【qmake】进行编译,以生成moc文件。然后再使用构建项目进行编译。

PS:Qt元对象系统


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI