使用Qtimer周期执行任务

头文件中:引用头文件

#include <QTimer>

头文件中:在类中创建Qtimer指针m_timer,创建返回该指针的方法get_timer().

点击查看代码
class SendFrameBox : public QGroupBox
{
    Q_OBJECT

public:
    explicit SendFrameBox(QWidget *parent = nullptr);
    void on_sendCyclic_clicked();
    void sendCyclicFrame();
    QTimer * get_timer() {return m_timer;}
    ~SendFrameBox();

signals:
    void sendFrame(const QCanBusFrame &frame);

private:
    Ui::SendFrameBox *m_ui = nullptr;

    HexIntegerValidator *m_hexIntegerValidator = nullptr;
    HexStringValidator *m_hexStringValidator = nullptr;
    QTimer *m_timer;
};

cpp文件中:定义全局变量,用于存放播放和暂停标志

bool isSending=false; //播放和暂停的标志位

cpp文件中:创建信号槽连接

connect(m_ui->sendButton_2, &QPushButton::clicked, this, &SendFrameBox::on_sendCyclic_clicked);
connect(m_timer, &QTimer::timeout, this, &SendFrameBox::sendCyclicFrame);

cpp文件中:完善槽函数内容

点击查看代码
void SendFrameBox::sendCyclicFrame()
{
    const uint frameId = m_ui->frameIdEdit_2->text().toUInt(nullptr, 16);
    QString data = m_ui->payloadEdit_2->text();
    const QByteArray payload = QByteArray::fromHex(data.remove(QLatin1Char(' ')).toLatin1());

    QCanBusFrame frame1 = QCanBusFrame(frameId, payload);
    frame1.setExtendedFrameFormat(m_ui->extendedFormatBox->isChecked());
    frame1.setFlexibleDataRateFormat(m_ui->flexibleDataRateBox->isChecked());
    frame1.setBitrateSwitch(m_ui->bitrateSwitchBox->isChecked());

    if (m_ui->errorFrame->isChecked())
        frame1.setFrameType(QCanBusFrame::ErrorFrame);
    else if (m_ui->remoteFrame->isChecked())
        frame1.setFrameType(QCanBusFrame::RemoteRequestFrame);
    emit sendFrame(frame1);
}

void SendFrameBox::on_sendCyclic_clicked()
{
    QIcon icon;
    if(isSending==false)
    {
        //开始周期发送
        isSending = true;
        get_timer()->start();
       icon.addFile(QString::fromUtf8(":/images/stop_icon.png"), QSize(), QIcon::Normal, QIcon::On);
        m_ui->sendButton_2->setIcon(icon);
    }
    else
    {
        //停止周期发送
        isSending = false;
        get_timer()->stop();
        icon.addFile(QString::fromUtf8(":/images/play_icon.png"), QSize(), QIcon::Normal, QIcon::On);
        m_ui->sendButton_2->setIcon(icon);
    }
}
posted @ 2025-06-17 09:11  ShererYANG  阅读(12)  评论(0)    收藏  举报