2023-08-10QT0

按下按钮打断某函数的执行
场景:读卡机循环读卡,现在需要外部打断
之前:

c
while(1){
    read();
}

用时钟,每1s触发一次函数,按按钮停止

c
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QTimer>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void outputText();
    void stopLoop();

private:
    Ui::MainWindow *ui;
    QTimer *timer;
    QPushButton *stopButton;
};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建定时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::outputText);

    // 创建按钮
    stopButton = new QPushButton("Stop", this);
    stopButton->setGeometry(10, 10, 80, 30);
    connect(stopButton, &QPushButton::clicked, this, &MainWindow::stopLoop);

    // 启动定时器
    timer->start(1000); // 每秒触发一次timeout信号
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::outputText()
{
    ui->textEdit->append("1");
}

void MainWindow::stopLoop()
{
    timer->stop(); // 停止定时器,终止循环输出
    ui->textEdit->append("Loop stopped.");
}

开线程进行操作,按按钮断掉线程(来源gpt)

c
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建按钮
    stopButton = new QPushButton("Stop", this);
    stopButton->setGeometry(10, 10, 80, 30);
    connect(stopButton, &QPushButton::clicked, this, &MainWindow::stopLoop);

    // 启动循环线程
    loopThread = new LoopThread(this);
    connect(loopThread, &LoopThread::textOutput, this, &MainWindow::outputText);
    loopThread->start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::outputText(const QString &text)
{
    ui->textEdit->append(text);
}

void MainWindow::stopLoop()
{
    loopThread->stop();
    ui->textEdit->append("Loop stopped.");
}
#include "loopthread.h"

LoopThread::LoopThread(QObject *parent) : QThread(parent), running(true)
{

}

void LoopThread::run()
{
    while (running) {
        emit textOutput("1");
        msleep(1000); // 等待1秒
    }
}

void LoopThread::stop()
{
    running = false;
}
#ifndef LOOPTHREAD_H
#define LOOPTHREAD_H

#include <QThread>

class LoopThread : public QThread
{
    Q_OBJECT
public:
    explicit LoopThread(QObject *parent = nullptr);

signals:
    void textOutput(const QString &text);

public slots:
    void stop();

protected:
    void run() override;

private:
    bool running;
};

#endif // LOOPTHREAD_H

本文作者:墨洺的文档

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!