Qt多线程程序设计中,可使用信号和槽进行线程通信
Qt多线程程序设计中,可使用信号和槽进行线程通信。下面是一个简单的示例。
该程序实现了线程中自定义一个信号和槽,定时1秒发送信号,槽响应后打印一条信息。
[cpp]view plaincopy
#include<QtCore/QCoreApplication>
#include<QThread>
#include<stdio.h>
classMyThread:publicQThread
{
Q_OBJECT
public:
MyThread();
voidstop();
private:
boolisRunning;
voidrun();
publicslots:
voidshowMsg();
signals:
voidmsg();
};
MyThread::MyThread()
{
isRunning=true;
connect(this,SIGNAL(msg()),this,SLOT(showMsg()),Qt::DirectConnection);
}
voidMyThread::showMsg()
{
printf("Hello!\n");
}
voidMyThread::run()
{
while(isRunning)
{
sleep(1);
emitmsg();
}
printf("Exit!\n");
}
voidMyThread::stop()
{
isRunning=false;
}
intmain(intargc,char*argv[])
{
QCoreApplicationa(argc,argv);
MyThreadmThread;
mThread.start();
while(1)
{
if(getchar()=='B')
{
mThread.stop();
mThread.wait();
break;
}
}
returna.exec();
}
#include"main.moc"
在Qt Creator中编译时,需先使用【qmake】进行编译,以生成moc文件。然后再使用构建项目进行编译。
PS:Qt元对象系统
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。