首先,需要创建一个类,继承于Qwidget,用于实现时间的获取界面。然后,在widget构造函数中new一个该类的对象,(widget类可以专门用来显示背景图片,通过重写paintevent()事件)则这个时间就显示到界面了。
创建该类,自定义名字为Main_Widget:
widget.h:
//类Main_Widget
//显示时间
#ifndef WIDGET_H
#define WIDGET_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
class Main_Widget : public QWidget
{
Q_OBJECT
public:
Main_Widget(QWidget *parent = 0);
~Main_Widget();
private:
QString date_string;
QString week_string;
QString time_string;
QLabel *date_label;
QLabel *week_label;
QLabel *time_label;
//定时器
QTimer * display_timer;
QLabel *display_Image;
QLabel *display_name;
private slots:
void Update_Time(void);
};
Main_Widget.cpp:
#include
#include "widget.h"
#include
Main_Widget::Main_Widget(QWidget *parent)
: QWidget(parent)
{
resize(1024,600); //set interface size
date_label = new QLabel(this);
week_label = new QLabel(this);
time_label = new QLabel(this);
//设置时间显示的大小
date_label->setParent(this);
display_timer = new QTimer(this);
connect(display_timer,SIGNAL(timeout()),this,SLOT(Update_Time()));
display_timer->start(1000); //after 1 S,restart Timer
date_label->setGeometry(20,100,200,50);
date_label->setStyleSheet("color:rgb(0, 0, 135);font-size:30px");
time_label->setGeometry(20,150,200,50);
time_label->setStyleSheet("color:rgb(0, 0, 135);font-size:50px");
week_label->setGeometry(20,200,200,50);
week_label->setStyleSheet("color:rgb(0, 0, 135);font-size:30px");
Update_Time();
}
//类Widget //只负责显示背景
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private:
Main_Widget * myMain_Widget;
protected:
void paintEvent(QPaintEvent *event);
};
#endif // WIDGET_H
//
void Main_Widget::Update_Time(void)
{
// time_label->clear();
QDateTime Current_time = QDateTime::currentDateTime();
// QString String_time = Current_time.toString("yyyy-MM-dd hh:mm:ss dddd");
date_string = Current_time.toString("yyyy-MM-dd");
qDebug()<<"date = "<
// qDebug()<<"date2= "<
// time_string = Current_time.toString("hh:mm:ss");
time_string = Current_time.toString("hh:mm");
date_label->setText(date_string);
week_label->setText(week_string);
time_label->setText(time_string);
// qDebug()<
}
Main_Widget::~Main_Widget()
{
delete date_label;
delete week_label;
delete time_label;
delete display_timer;
}
widget.cpp:
#include "widget.h"
//只是负责主界面的背景
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
setWindowTitle("Main Interface");
//设置窗口无边框
setWindowFlags(Qt::FramelessWindowHint);
resize(1024,600); //set interface size
myMain_Widget = new Main_Widget(this);
}
//重写了paintEvent()事件
void Widget::paintEvent(QPaintEvent * event)
{
QPainter painter(this);
painter.drawPixmap(0,0,this->width(),this->height(),QPixmap(":/Images/3.jpg"));
}
Widget::~Widget()
{
delete myMain_Widget;
}
主函数:
//主函数
#include
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget myWidget;
myWidget.show();
return a.exec();
}