7.多线程实现定时发送

多线程实现定时发送

1.创建一个自定义线程

  • 自定义一个线程继承QThread,重新run()
  • run()中使用定时msleep(1000);并发送信号threadTimeOut
  • 定义一个信号threadTimeOut

customthread.h

#ifndef CUSTOMTHREAD_H
#define CUSTOMTHREAD_H

#include <QThread>
#include <QWidget>

class CustomThread : public QThread
{
    Q_OBJECT
public:
    CustomThread(QWidget *parent);
protected:
    void run() override;
signals:
    void threadTimeOut();
};

#endif // CUSTOMTHREAD_H

customthread.cpp

#include "customthread.h"

CustomThread::CustomThread(QWidget *parent):QThread(parent)
{

}

void CustomThread::run()
{
    while (true) {
        msleep(1000);
        emit threadTimeOut();
    }
}

2.widget中实现

widget.h

class Widget : public QWidget
{
private slots:
	void on_checkBox_sendRound_clicked(bool checked);
    void button_handle();
private:
	int buttonIndex = 0;
    CustomThread *buttonsThread;
}

widget.cpp

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    buttonsThread = new CustomThread(this);
    connect(buttonsThread,&CustomThread::threadTimeOut,this,&Widget::button_handle);
    
    for (int i = 1; i <= 9; i++) {
        QString btnName = QString("pushButton_%1").arg(i);
        QPushButton* btn = findChild<QPushButton *>(btnName);
        if(btn) {
            btn->setProperty("buttonId",i);
            buttons.append(btn);
            connect(btn,SIGNAL(clicked()),this,SLOT(on_command_button_clicked()));
        }
    }
}

void Widget::button_handle()
{
    if(buttonIndex < buttons.size())
    {
        QPushButton *btn =  buttons[buttonIndex];
        emit btn->clicked();
        buttonIndex++;
    }else{
        buttonIndex = 0;
    }
}

void Widget::on_checkBox_sendRound_clicked(bool checked)
{
    if(checked)
    {
        buttonsThread->start();
    }else{
        buttonsThread->terminate();
    }
}
posted @ 2025-05-09 11:53  站着说话不腰疼  阅读(35)  评论(0)    收藏  举报