用QT写一段画时钟的程序
很高兴为您提供以下代码段,这是使用QT编写的简单时钟程序:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QTimer *timer;
private slots:
void updateTime();
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 创建一个定时器,每秒钟更新一次时间
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()));
timer->start(1000);
// 初始化时钟
updateTime();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateTime()
{
// 获取当前时间
QDateTime currentTime = QDateTime::currentDateTime();
QString timeStr = currentTime.toString("hh:mm:ss");
// 更新时钟显示
ui->label->setText(timeStr);
}
此时钟程序包括一个QLabel小部件,用于显示当前时间。在构造函数中,我们创建一个QTimer并连接其timeout()信号到updateTime()槽,以在每秒钟更新时间。updateTime()槽获取当前时间,并将其格式化为字符串,然后将其设置为QLabel的文本。
您可以将此代码复制并粘贴到您的QT项目中,然后构建和运行它以查看时钟的工作原理。
原文地址: https://www.cveoy.top/t/topic/bDng 著作权归作者所有。请勿转载和采集!