c++ - QTimer 启动函数到底发生了什么?

标签 c++ qt

我有以下代码:

mytimer.cpp

#include "mytimer.h"
#include <QtCore>
MyTimer::MyTimer()
{
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(mySlot()));
    timer->start(1000);    
}

void MyTimer::mySlot()
{
    qDebug()<<"timer executed";

}

并且在 ma​​in.cpp

#include <QCoreApplication>
#include "mytimer.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyTimer mtimer;
    qDebug()<<"DONE";

    return a.exec();
}

现在输出如下:

DONE
timer executed
timer executed
...
...
...
...
infinite sequence

我真的很困惑。我们如何完成我们的 main 函数并且仍然执行 SLOT mySlot() 的代码?

这有哪些重要方面?我需要了解什么?

另外,当我将 mytimer.cpp MyTimer() 修改为:

时会发生什么变化:
MyTimer::MyTimer()
{
    timer = new QTimer(this);
    QEventLoop eventloop;
    connect(timer,SIGNAL(timeout()),this,SLOT(mySlot()));
    connect(timer,SIGNAL(timeout()),&eventloop,SLOT(quit()));
    timer->start(1000);
    eventloop.exec();
}

在打印DONE 之前有一个计时器执行。具体来说,输出现在变为:

timer executed
DONE
timer executed
timer executed
...
...
...
...
infinite sequence

是什么导致那个单独的timer executed 出现在DONE 之上?

最佳答案

否 - 您的主要功能尚未完成。它调用了 a.exec(),它永远不会在您的应用程序中返回。

a.exec() 依次处理一个“消息队列”,它触发所有调用 mySlot() 的定时器事件。

关于c++ - QTimer 启动函数到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42051724/

相关文章:

c++ - 如何通过其 HWND 句柄更改另一个进程中 TDateTimePicker 控件中当前选定的日期?

C++ 将类映射到数字

python - Qt 启动画面未在 python 中显示

c++ - QT 4.5 - QGraphicsItem 分配给 0x0 的父场景

c++ - Qt - 摆脱 .dll 文件丢失错误

c++ - 初学者 C++ 数组和循环?

c++ - 基类复制构造函数的可见性问题

c++ - 将 ip 解析为主机名

qt - 在 dropEvent 中删除 QFrame 子类时,内部 QMutex::lock 崩溃

c++ - 将类函数连接到按钮。(QT C++)