QT按钮/停止按钮

QT push button / stop button

我有一个按钮,我想在单击时将其更改为停止按钮。当前按钮的文本显示 "auto fire",它会无限循环,单击时文本会变为 "stop auto fire"。我的问题是在文本更改后再次通过 clicking/pressing 此按钮打破无限循环。

到目前为止的代码:

void Cpp_Fire::on_auto_fire_clicked()
{
    while(true)
    {
        ui->auto_fire->setText("Stop Auto Fire");
        on_manual_fire_clicked();
    }
}

我尝试在上面的循环中插入一个不同的插槽,该循环在按下按钮后运行(确切地说,它在释放按钮时运行),但我无法让它工作。 我知道这可以通过 signals/slots 和一个单独的停止按钮来完成,但我不熟悉该方法,我更喜欢我描述的方法。

无限循环的问题是没有其他任何东西有机会工作。

您可以使用的一种方法是使用具有短间隔的 QTimer 来调用 on_manual_fire_clicked() 方法,然后让 on_auto_fire_clicked() 方法负责更改按钮和启用/禁用定时器。

如果您这样做,ui 应该有足够的时间来响应点击等。

编辑:

有关使用 QTimer 的更多信息,请查看此页面:

How to use QTimer

或本教程:

http://www.bogotobogo.com/Qt/Qt5_QTimer.php

这是一些代码:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();
    void timerslot();

private:
    Ui::MainWindow *ui;

    QTimer* myTimer;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QTimer>
#include<QDebug>

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

    myTimer = new QTimer(this);
    myTimer->setInterval(500);
    myTimer->setSingleShot(false);
    connect(myTimer, SIGNAL(timeout()), this, SLOT(timerslot()));
    myTimer->start();
}

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

void MainWindow::timerslot()
{
    qDebug() << "timeslot";
}

void MainWindow::on_pushButton_clicked()
{
    if ( this->myTimer->isActive() == true ) {
        this->myTimer->stop();
        ui->pushButton->setText("Start");
    } else {
        this->myTimer->start(500);
        ui->pushButton->setText("Stop");
    }
}

希望您能理解并能将其转化为您的需求。

我完全同意迈克尔的回答。

  • 这也会影响重绘! (尝试在您的应用程序上放置一些 windows,而在无限循环中:您应该会看到重绘问题)。

  • 不要使用无限循环,特别是不要在插槽内使用!

  • 尝试QTimer,或将对象移动到QThread

  • 在这样的循环中:给 GUI-Thread 一些时间。你可以打电话给QCoreApplication::processEvents().。但是要小心。

使用 QTimer 的简单(仍然很差)解决方案可能是: (我发现,迈克尔在他的回答中输入了一个例子。-使用它。)。

//have a QTimer 'timer' in the class, and a connect signal 
//timer.timeout() to 'onSingleShotFired()'
void Cpp_Fire::on_auto_fire_clicked()
{
    if ( ui->auto_fire->text() == "Stop Auto Fire" )
    {    
        timer.stop();
        ui->auto_fire->setText("Start Auto Fire");
    } 
    else 
    {
        //MSEC_AUTOFIRE_DELAY is the delay between the autofire-shots
        timer.start( MSEC_AUTOFIRE_DELAY );
        ui->auto_fire->setText("Stop Auto Fire");
    }
}