#ifndef TIME_H
#define TIME_H
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QString>
#include <QTime>
class Time : public QWidget
{
Q_OBJECT
public:
Time(QWidget *parent = 0);
~Time();
private:
QString string;
QLabel* label;
QPushButton* button;
public slots://自定义槽函数
void ShowTime(void);
signals://自定义信号函数,只需要声明,不能写定义
void mySignal(const QString&);
};
#endif // TIME_H
#include "Time.h"
#include <QDebug>
Time::Time(QWidget *parent)
: QWidget(parent)
{
this->resize(300,200);
label = new QLabel(this);
label->setFrameStyle(QFrame::Panel|QFrame::Sunken);//面板|凹陷
label->setAlignment(Qt::AlignCenter|Qt::AlignVCenter);//水平|垂直居中
QFont font;
font.setPointSize(20);//调整字体大小
label->setFont(font);
button = new QPushButton("Current Time",this);
button->setFont(font);//保持字体大小一致
// connect(button,SIGNAL(clicked(void)),this,SLOT(ShowTime(void)));
connect(button,SIGNAL(clicked(void)),this,SLOT(ShowTime(void)));
//通过自定义信号,触发label的setText槽函数执行
connect(this,SIGNAL(mySignal(QString)),label,SLOT(setText(QString)));
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(label);
layout->addWidget(button);
this->setLayout(layout);
}
void Time::ShowTime(void)
{
qDebug() << "ShowTime";
QTime time = QTime::currentTime();//获取当前时间
string = time.toString("hh:mm:ss");//把时间按指定格式转为字符串
//string = time.toString(Qt::TextDate);//把时间转为字符串
//label->setText(string);//显示时间字符串
emit mySignal(string);//emit是qt关键字,标记发射信号
}
Time::~Time()
{
}
#include "Time.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Time w;
w.show();
return a.exec();
}