Qtimer使用多次connect的误区

本人目前小白一枚,所及问题只为方便查看,忘大神们勿喷,有指导意见的本人会很高兴(〃'▽'〃)

在使用一个定时器时多次调用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();
}

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值