以下是一个用QT开启线程实现定时通信并保存结果的示例代码:
#include <QThread>
#include <QTimer>
class CommunicationThread : public QThread
{
Q_OBJECT
signals:
void resultSaved(QString result);
private:
QString m_result;
protected:
// 线程执行函数
void run() override
{
// 建立一个定时器,每2秒触发一次timeout()信号
QTimer timer;
connect(&timer, &QTimer::timeout, this, &CommunicationThread::communication);
timer.start(2000);
exec();
}
// 通信函数
void communication()
{
// 进行通信操作,这里简化为输出一句话
qDebug() << "Communication executed.";
// 把通信结果保存起来
m_result = "Communication executed.";
// 发送resultSaved信号,把结果传递给主线程
emit resultSaved(m_result);
}
};
// 主线程
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CommunicationThread thread;
// 连接resultSaved信号,把结果保存到文件中
QObject::connect(&thread, &CommunicationThread::resultSaved, [](QString result){
QFile file("result.txt");
if (file.open(QIODevice::Append | QIODevice::Text)) {
QTextStream out(&file);
out << result << "\n";
}
});
// 开始执行线程
thread.start();
return a.exec();
}
#include "main.moc"
在上面的示例代码中,我们继承了QThread类,并实现了一个名为communication()的函数,用于模拟通信操作。在run()函数中,我们建立了一个定时器,每2秒触发一次timeout()信号,然后执行exec()函数来让线程进入事件循环状态。
当定时器触发timeout()信号时,我们会调用communication()函数进行通信操作,并把通信结果保存到成员变量m_result中。然后,我们通过发射resultSaved信号,把结果传递给主线程。
在主线程中,我们连接了resultSaved信号和一个lambda表达式。在这个lambda表达式中,我们把结果保存到文件中。最后,我们开启了线程并进入事件循环状态。
需要注意的是,在Qt5之前,我们需要用Q_DECLARE_METATYPE宏定义QString类型,以便能够在信号和槽之间传递该类型的参数。在Qt5及以后版本中,已经无需使用该宏定义了。