歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Qt中使用QLabel顯示時間的兩種方法

Qt中使用QLabel顯示時間的兩種方法

日期:2017/3/1 9:47:55   编辑:Linux編程

Qt中使用QLabel顯示時間的兩種方法思路一致,只是實現方法不一樣而已。

main.cpp

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

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

return a.exec();
}

方法一:

displaytime.h

#ifndef DISPLAYTIME_H
#define DISPLAYTIME_H

#include <QWidget>
#include <QtGui>

class QLabel;

class DisplayTime : public QWidget
{
Q_OBJECT

public:
DisplayTime(QWidget *parent = 0);
~DisplayTime();

private:
QLabel *timeLabel;

protected:
void timerEvent(QTimerEvent * event);
};

#endif // DISPLAYTIME_H

displaytime.cpp

#include "displaytime.h"

DisplayTime::DisplayTime(QWidget *parent)
: QWidget(parent)
{
timeLabel = new QLabel(this);
timerEvent(0);
startTimer(1000);
timeLabel->show();
}

DisplayTime::~DisplayTime()
{

}

void DisplayTime::timerEvent(QTimerEvent *event)
{
Q_UNUSED(event);
timeLabel->setText(QTime::currentTime().toString("hh:mm:ss"));
}

方法二:

displaytime.h

#ifndef DISPLAYTIME_H
#define DISPLAYTIME_H

#include <QWidget>
#include <QtGui>

class QLabel;

class DisplayTime : public QWidget
{
Q_OBJECT

public:
DisplayTime(QWidget *parent = 0);
~DisplayTime();

private:
QLabel *timeLabel;

private slots:
void updateTime();
};

#endif // DISPLAYTIME_H

displaytime.cpp

#include "displaytime.h"

DisplayTime::DisplayTime(QWidget *parent)
: QWidget(parent)
{
timeLabel = new QLabel(this);
timeLabel->setGeometry(0, 0, 150, 30);

QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),
this, SLOT(updateTime()));
timer->start(1000);

timeLabel->show();
}

DisplayTime::~DisplayTime()
{

}

void DisplayTime::updateTime()
{
timeLabel->setText(QDateTime::currentDateTime().toString("hh:mm:ss"));
}

Qt 的詳細介紹:請點這裡
Qt 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved