QT在执行程序时,无论时窗体应用程序还是控制台应用程序,都是以消息循环机制执行的,程序执行完成后,需要退出消息循环后程序才算真正执行完成。

退出QT程序可以使用一个QT提供的全局指针变量qApp实现,但还需要配合QTimer来完成。

 

总结

 此例中,在主函数中执行完主要的任务run函数后,调用退出函数quitApp,定时器m_Timer启动,此例设置为10ms(具体值可以自行设置),定时器超时后调用qApp->exit(0)函数,程序退出。

 

myclass.h

 

 1 #ifndef MYCLASS_H
 2 #define MYCLASS_H
 3 
 4 #include <QObject>
 5 #include <QTimer>
 6 
 7 class MyClass : public QObject
 8 {
 9     Q_OBJECT
10 public:
11     explicit MyClass(QObject *parent = nullptr);
12     void run();
13     void quitApp();
14 
15 signals:
16 
17 private:
18     QTimer m_Timer;
19 
20 };
21 
22 #endif // MYCLASS_H

 

 

 myclass.cpp 

 1 // myclass.cpp
 2 
 3 #include "myclass.h"
 4 #include "QCoreApplication"
 5 
 6 MyClass::MyClass(QObject *parent)
 7     : QObject{parent}
 8 {
 9     connect(&m_Timer, &QTimer::timeout, this, [&](){
10         // 退出程序
11         qApp->exit(0);
12     });
13 }
14 
15 void MyClass::run()
16 {
17     // 执行主要的程序
18 }
19 
20 
21 // 退出程序
22 void MyClass::quitApp()
23 {
24     // 启动定时器
25     m_Timer.start(10);
26 }

 

  myclass.cpp  

 1 // main.cpp
 2 
 3 #include <QCoreApplication>
 4 #include <myclass.h>
 5 
 6 int main(int argc, char *argv[])
 7 {
 8     QCoreApplication a(argc, argv);
 9 
10     MyClass task;
11 
12     // 执行主要任务
13     task.run();
14 
15     // 程序执行完毕后退出
16     task.quitApp();
17 
18     return a.exec();
19 }

 

 

 

1. 在执行主任务或者完成最后任务的自定义类中设置一个定时器

 

 

 

 

 

2. 将定时器的超时信号与Qt提供的全局变量的退出函数绑定

 

 

 注意:使用全局变量qApp时必须包含相关头文件,具体的头文件需与主函数中的一致

 

 

3. 在程序执行完成时启动定时器,定时器超时后发送超时信号,调用全局变量qApp的退出函数。

此处我们在自定义类中定义了一个quitApp的函数来执行,在quitApp主要作用是用于启动定时器。

 

 

 

总结

 此例中,在主函数中执行完主要的任务run函数后,调用退出函数quitApp,定时器m_Timer启动,此例设置为10ms(具体值可以自行设置),定时器超时后调用qApp->exit(0)函数,程序退出。

posted on 2022-08-08 11:12  大王背我来巡山®  阅读(749)  评论(0编辑  收藏  举报