主程序
#include <QCoreApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MainWindow w;
return a.exec();
}
mainwindow.cpp程序
#include "mainwindow.h"
#include <QDateTime>
MainWindow::MainWindow(QObject *parent)
:QObject(parent)
{
pTimer = new QTimer(this);
pTimer->setInterval(10000);
connect(pTimer, &QTimer::timeout, this, &MainWindow::slot10000msTimeOut);
pTimer->start();
qDebug() << "Start constructing MainWindow at:" << QDateTime::currentDateTime();
if (pTimer->isActive()) {
qDebug() << "Timer started successfully.";
} else {
qDebug() << "Timer failed to start.";
}
}
MainWindow::~MainWindow()
{
if(pTimer->isActive()){
pTimer->stop();
}
}
void MainWindow::slot10000msTimeOut()
{
qDebug() << "End constructing MainWindow at:" << QDateTime::currentDateTime();
}
mainwindow.h头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
#include <QDebug>
class MainWindow : public QObject
{
Q_OBJECT
public:
MainWindow(QObject *parent = nullptr);
~MainWindow();
private:
QTimer *pTimer;
private slots:
void slot10000msTimeOut();
};
#endif // MAINWINDOW_H
总结了注意点:
关闭定时器,在程序结束的时候,再stop
声明了槽函数,是必须要去定义的。否则报错
QCoreApplication不依赖于任何 GUI 相关的库和功能