0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Qt】Qtでデジタル時計を表示してみた【C++】

Last updated at Posted at 2025-07-30

Qtでデジタル時計を表示してみました。

内容は以下になります。

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLCDNumber>
#include <QTimer>

class MainWindow : public QMainWindow
{
    Q_OBJECT  

    public:
        MainWindow(QWidget *parent = nullptr); 
        ~MainWindow();                         

        private slots:
            void updateTime(); // 時間を更新する関数

    private:
        QLCDNumber *lcd; // 時間を表示するLCD風の表示部品
        QTimer *timer;   // 時間を更新するためのタイマー
};

#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <QTime>         // 現在の時間を取得するため
#include <QVBoxLayout>   // レイアウト

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // 中央に表示するウィジェットを作成
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget); // centralWidget に設定

    // デジタル時計の表示を作成
    lcd = new QLCDNumber(8, this);        // 8桁表示(hh:mm:ss)
    lcd->setSegmentStyle(QLCDNumber::Filled); // セグメントのスタイルを「塗りつぶし」に
    lcd->setDigitCount(8);               // 桁数設定

    // タイマーを作成して1秒ごとに updateTime() を呼ぶ
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateTime);
    timer->start(1000); // 1000ミリ秒(=1秒)ごと

    // レイアウトを使ってlcdを画面に配置
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(lcd); // LCDをレイアウトに追加
    centralWidget->setLayout(layout); // レイアウトを centralWidget にセット

    // 初回表示(起動直後に表示が空白にならないように)
    updateTime();

    // ウィンドウタイトルやサイズを設定
    setWindowTitle("デジタル時計");
    resize(250, 100);
}

MainWindow::~MainWindow()
{
}

// 現在の時間を取得してLCDに表示する関数
void MainWindow::updateTime()
{
    QString timeText = QTime::currentTime().toString("hh:mm:ss"); // 時刻を文字列に変換
    lcd->display(timeText); // LCDに表示
}

↓↓youtube
https://youtu.be/hoNTWd9mBpI

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?