Qt中静态方法发送信号

19 篇文章 0 订阅

背景:线程中开启了定时器,轮询传感器状态,传感器状态的获取是使用的静态方法,想要达到的效果是,一旦传感器满足阈值,就发送特定信号,界面类接收到这个信号后,实时显示弹窗(警告或提醒)。尝试过各种方法都不能奏效,最后验证此方法可行,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;
}


}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雲烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值