本人目前小白一枚,所及问题只为方便查看,忘大神们勿喷,有指导意见的本人会很高兴(〃'▽'〃)
在使用一个定时器时多次调用start()和stop()时完全没有问题的,先讲一下是start()的作用:
Qt的帮助文档如下:
This is an overloaded function.
Starts or restarts the timer with a timeout of duration msec milliseconds.
If the timer is already running, it will be stopped and restarted.
If singleShot is true, the timer will be activated only once.
也就是说每次调用start ()如果定时器仍在运行,将会被停止,再开启(此时重新计数)。
下面是我的问题
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timer = new QTimer(this);
timer->setSingleShot(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
connect(timer,&QTimer::timeout,this,&MainWindow::add);
timer->start(3000);
}
void MainWindow::add()
{
if(timer->isActive()){
timer->stop();
}
ui->textEdit->append(tr("123"));
}
void MainWindow::on_pushButton_2_clicked()
{
if(timer->isActive())
timer->stop();
}
我希望没点一次按键,3s后增加一次“123”,所以在点击事件中start()并connect(),这就导致增加“123”的数量会随着点击按键的次数增加。这是因为此时程序没点击一次就会建立一次新的connect(),所以应保证connect仅执行一次。程序修改如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer,&QTimer::timeout,this,&MainWindow::add);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
timer->start(3000);
}
void MainWindow::add()
{
if(timer->isActive()){
timer->stop();}
ui->textEdit->append(tr("123"));
}
void MainWindow::on_pushButton_2_clicked()
{
if(timer->isActive())
timer->stop();
}