背景:线程中开启了定时器,轮询传感器状态,传感器状态的获取是使用的静态方法,想要达到的效果是,一旦传感器满足阈值,就发送特定信号,界面类接收到这个信号后,实时显示弹窗(警告或提醒)。尝试过各种方法都不能奏效,最后验证此方法可行,connect函数写在ui的构造函数中,所以在此之前要完成信号的发射。
首先,定义自己使用的定时器线程。
#ifndef MY_THREAD_H
#define MY_THREAD_H
#include<QTimer>
#include<QThread>
class MyThread:public QThread
{
Q_OBJECT
public slots:
static void timeOutHandle(void);
void testPrintSlots(void);
public:
MyThread(QObject* parent = nullptr);
void run();
QTimer * threadTimer;
static MyThread* MyPointer;
static void testPrintFunc(void);
signals:
void isDone();
void testPrintSignal(void);
};
#endif // MY_THREAD_H
其中,类中*myPointer指针非常重要,是发送信号的关键,不然connect函数会报错,或者编译时报错。它的作用就是将this指针赋值给自己。
#include"my_thread.h"
#include"exec_shell.h"
#define MYTHREADTIMER 1000 //ms
MyThread * MyThread::MyPointer =nullptr;
MyThread::MyThread(QObject* parent ):QThread(parent)
{
MyPointer = this;
}
void MyThread::run()
{
qDebug()<<" !MyThread::run()"<<endl;
threadTimer = new QTimer();
threadTimer->setInterval(MYTHREADTIMER);
connect(threadTimer, &QTimer::timeout, &MyThread::timeOutHandle);
threadTimer->start();
this->exec();
}
void MyThread::timeOutHandle()
{
qDebug()<<"!! MyThread::timeOutHandle()"<<endl;
testPrintFunc();
}
void MyThread::testPrintFunc()
{
qDebug()<<"!!! MyThread::testPrintFunc()"<<endl;
emit MyPointer->testPrintSignal();
}
void MyThread::testPrintSlots()
{
qDebug()<<"@@@@MyThread::testPrintSlots()"<<endl;
}
注意,通过myPointer指针来找到类中的信号,就不会出现此函数是非静态函数的错误警告。就是这一句:
emit MyPointer->testPrintSignal();
最后,在ui的cpp文件的构造函数中去连接这个发出的信号即可。
#include "dialogtest.h"
#include "ui_dialogtest.h"
#include"my_thread.h"
#include<QDebug>
Dialogtest::Dialogtest(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialogtest)
{
ui->setupUi(this);
qDebug("$$$$Dialogtest");
connect(MyThread::MyPointer, &MyThread::testPrintSignal, this, [=](){
qDebug()<<"ccccccc"<<endl;
Dialogtest:: MyTestSlots();
});
}
Dialogtest::~Dialogtest()
{
delete ui;
}
void Dialogtest:: MyTestSlots()
{
qDebug()<<"!!!!!Dialogtest:: MyTestSlots()"<<endl;
}
完结,在main.cpp中实例化自定义线程类即可,即实现了在线程中开启定时器并发送信号。
#include "mainwindow.h"
#include <QApplication>
#include"calendordlg.h"
#include"my_thread.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
calendorDlg * dlg = new calendorDlg;
auto timeEventLoop = new MyThread();
timeEventLoop->start();
if(dlg->exec() == QDialog::Accepted){
w.show();
return a.exec();
}else {
return 0;
}
}