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元对象系统