溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Qt多線程程序設計中,可使用信號和槽進行線程通信

發(fā)布時間:2020-07-13 19:09:31 來源:網(wǎng)絡 閱讀:1012 作者:WZM3558862 欄目:開發(fā)技術

Qt多線程程序設計中,可使用信號和槽進行線程通信。下面是一個簡單的示例。

該程序?qū)崿F(xiàn)了線程中自定義一個信號和槽,定時1秒發(fā)送信號,槽響應后打印一條信息。

[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元對象系統(tǒng)


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI