QT版用QLCDnumber顯示時間

我只想copy發表於2017-12-09

/*基於qt5.7

*無需ui介面

*資料是百度和自幾學到的,不多

*僅供參考

*不喜隨便噴,反正我也不看,哈啊啊、

*/

//首先是dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QLCDNumber>
#include <QTime>
#include <QTimer>
#include <QPalette>
#include <QVBoxLayout>
#include <QHBoxLayout>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
public slots:
    void showTime();

private:
    Ui::Dialog *ui;
    QLCDNumber *time;
    QTime tim;
    QTimer *timer;
};

#endif // DIALOG_H

//接著是dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"


Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    resize(200,200);            //設定生成介面的大小,可以拖邊框改變介面大小
    time = new QLCDNumber(this);
    time->setDigitCount(8);     //設定lcd裡面的個數,格式是hh:mm:ss,總的是八個。所以設定為8
    time->setFixedSize(80, 60); //設定大小
    time->setPalette(Qt::cyan); //設定顏色

    QVBoxLayout *vbox = new QVBoxLayout;
    QHBoxLayout *hbox = new QHBoxLayout;
    vbox->addWidget(time);
    hbox->addLayout(vbox);
    setLayout(hbox);   //設定佈局,將lcd空間放到中間

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));  //用一個定時訊號來更改時間
    timer->start(500);  //啟動定時
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::showTime()
{
    tim = QTime::currentTime();  //獲取當地時間
    QString timestr = tim.toString("hh:mm:ss"); //設定時間格式
    time->display(timestr);  //顯示時間
}

//mian.cpp

#include "dialog.h"
#include <QApplication>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}


相關文章