Qt多线程程序设计中,可使用信号和槽进行线程通信。下面是一个简单的示例。
该程序实现了线程中自定义一个信号和槽,定时1秒发送信号,槽响应后打印一条信息。
[cpp] view plain copy
- #include <QtCore/QCoreApplication>
- #include <QThread>
- #include <stdio.h>
- class MyThread:public QThread
- {
- Q_OBJECT
- public:
- MyThread();
- void stop();
- private:
- bool isRunning;
- void run();
- public slots:
- void showMsg();
- signals:
- void msg();
- };
- MyThread::MyThread()
- {
- isRunning = true;
- connect(this,SIGNAL(msg()),this,SLOT(showMsg()),Qt::DirectConnection);
- }
- void MyThread::showMsg()
- {
- printf("Hello!\n");
- }
- void MyThread::run()
- {
- while(isRunning)
- {
- sleep(1);
- emit msg();
- }
- printf("Exit!\n");
- }
- void MyThread::stop()
- {
- isRunning = false;
- }
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- MyThread mThread;
- mThread.start();
- while(1)
- {
- if(getchar()==‘B‘)
- {
- mThread.stop();
- mThread.wait();
- break;
- }
- }
- return a.exec();
- }
- #include "main.moc"
在Qt Creator中编译时,需先使用【qmake】进行编译,以生成moc文件。然后再使用构建项目进行编译。
PS:Qt元对象系统
时间: 2024-12-06 02:19:20