mainwindow.cpp的实现
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// time.setHMS(0,0,0,0);//设置初始值
timer = new QTimer(this);//创建一个定时器
connect(timer, SIGNAL(timeout()), this, SLOT(update1()));//手动连接槽函数
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
timer->start(1);
}
void MainWindow::on_pushButton_2_clicked()
{
timer->stop();
}
void MainWindow::update1(){
time = QTime::currentTime();
static quint32 time_out=0;
time_out++;
time=time.addMSecs(1);
ui->label->setText(time.toString("hh:mm:ss:zzz"));
// ui->label->update();
qDebug() << time.toString("hh:mm:ss:zzz");
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTime>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
QTimer *timer;
QTime time;
private slots:
void on_pushButton_clicked();
void update1();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
主要用到QTimer和QTime
具体实例: