开发平台: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