在前文基础上:
再拓展一下,使用自定义信号:
TimeDialog.h
#ifndef __TIMEDIALOG_H
#define __TIMEDIALOG_H
#include<QDialog>
#include<QLabel>
#include<QPushButton>
#include<QVBoxLayout> //垂直布局器
#include<QTime>
#include<QDebug>
class TimeDialog:public QDialog
{
Q_OBJECT //moc
private:
QLabel* m_label;//显示时间
QPushButton* m_button;
public:
TimeDialog(void);
public slots:
//获取系统时间的槽函数
void getTime(void);
signals:
//自定义信号函数,只需声明,不能写定义
void mySignal(const QString&);
};
#endif
TimeDialog.cpp
#include"TimeDialog.h"
#include<QFont>
//构造函数
TimeDialog::TimeDialog(void)
{
//初始化界面
m_label = new QLabel(this);
m_label->setFrameStyle(QFrame::Panel | QFrame::Sunken);//凹陷面板
m_label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
//设置label的字体大小
QFont font;
font.setPointSize(20);
m_label->setFont(font);
//获取系统时间的按钮
m_button = new QPushButton("获取当前时间",this);
m_button->setFont(font);
//创建垂直布局器
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_label);
layout->addWidget(m_button);
//设置布局器
setLayout(layout);
//信号和槽函数
connect(m_button, SIGNAL(clicked(void)), this, SLOT(getTime(void)));
//通过自定义信号,触发label的setText槽函数执行
connect(this, SIGNAL(mySignal(QString)), m_label, SLOT(setText(QString)));
}
//获取系统时间的槽函数
void TimeDialog::getTime(void)
{
qDebug("getTime");
//qDebug()<<"getTime";
//获取当前系统时间
QTime time = QTime::currentTime();
//将时间对象转换为字符串
QString str = time.toString("h:m:s ap");
//显示时间
//m_label->setText(str);
//emit:是Qt关键字,标记当前是发射信号
emit mySignal(str);//发射信号
}
main.cpp
#include<QApplication>
#include"TimeDialog.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
TimeDialog time;
time.show();
return app.exec();
}