4、Qt--bug之在for循环中错误使用return导致代码未执行

开发平台:Win10 64位
开发环境:Qt Creator 13.0.0
构建环境:Qt 5.15.2 +MSVC2019 64位

项目场景:

项目场景:使用Timer的startTimer定时执行一段代码,其中startTimer是在MainWindow构造函数中实现的,时间间隔是100ms,然后通过timerEvent去执行定时代码。


问题描述

例如:在运行时发现timerEvent中代码并没有执行,使用qDebug()调试也不输出内容,将qDebug()位置放在for循环的前面就可以,放在后面就没有调试数据输出。
MainWindow.cpp中代码:

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

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<QLabel *> LBlist = ui->centralwidget->findChildren<QLabel*>();
    for(auto lb :LBlist)
    {
        qDebug()<<lb->objectName();
        if(lb->objectName()=="label_2")
        {
            return;
        }
        lb->setStyleSheet("");
    }
    qDebug()<<"1111";
    //timerid1 = startTimer(100);
    //timerid2 = startTimer(3000);
}

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

void MainWindow::timerEvent(QTimerEvent *e)
{
    if(e->timerId()==timerid1)
    {
        qDebug("1");
    }
    else if(e->timerId()==timerid2)
    {
        qDebug("2");
    }
}


原因分析:

for循环中的return导致的,return执行后就不会执行for之后的代码了,所以将qDebug()放在for循环之前就能输出调试信息,放在qDebug之后就有可能不输出,就是return结束了MainWindow函数导致的。

ps:return语句用于结束当前正在执行的函数,并将控制权返回给调用此函数的函数。

解决方案:

for循环中不使用return来结束本次循环,而是用continue来结束本次循环,开启下次循环。

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

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<QLabel *> LBlist = ui->centralwidget->findChildren<QLabel*>();
    for(auto lb :LBlist)
    {

        if(lb->objectName()=="label_2")
        {
            continue;
        }
    }
    qDebug()<<"1111";
    //timerid1 = startTimer(100);
    //timerid2 = startTimer(3000);
}

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

void MainWindow::timerEvent(QTimerEvent *e)
{
    if(e->timerId()==timerid1)
    {
        qDebug("1");
    }
    else if(e->timerId()==timerid2)
    {
        qDebug("2");
    }
}


参考文献:

https://blog.csdn.net/mlyjqx/article/details/61621977
https://blog.csdn.net/qq_30546099/article/details/128344080

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值