运用定时器事件实现 闹钟项目
主要代码:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
, spk(new QTextToSpeech(this))
{
ui->setupUi(this);
this->setWindowFlag(Qt::FramelessWindowHint);
this->setAttribute(Qt::WA_TranslucentBackground);
timer1 =new QTimer(this);
connect(timer1,&QTimer::timeout,this,&Widget::timeout_slot);
timer1->start(1000);
tex="起床了,太阳晒屁股了\n";
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_2_clicked()
{
qDebug() << "程序已退出";
this->close();
}
void Widget::on_pushButton_clicked()
{
if(ui->pushButton->text()=="启动")
{
int msec;
QTime cur_time=QTime::currentTime();
QTime set_time=ui->timeEdit->time();
ui->label_4->setText("倒计时!!!");
if(cur_time<set_time)
{
msec=cur_time.msecsTo(set_time);
}
else
{
msec=cur_time.msecsTo(set_time)+24*3600*1000;
}
id=startTimer(msec);
ui->pushButton->setText("关闭");
}
else
{
//ui->label_4->clear();
b=0;a=0;
tex="起床了,太阳晒屁股了\n";
ui->label_4->setText("闹钟!!!");
killTimer(id);
ui->pushButton->setText("启动");
}
}
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId()==id)
{
ui->label_4->setText(tex);
spk->say(ui->label_4->text());
killTimer(id);
b=1;
}
}
void Widget::timeout_slot()
{
QTime s_time=QTime::currentTime();
QString t = s_time.toString("hh : mm : ss");
ui->label->setText(t);
ui->label->setAlignment(Qt::AlignCenter);
if(b==1){
if(a<21)
{ a++;
if(a%5==0){
tex+="起床了,太阳晒屁股了\n";
ui->label_4->setText(tex);
spk->say("起床了,太阳晒屁股了\n");
}
}
}
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons()==Qt::LeftButton)
{
this->move(event->globalPos()-p);
}
}
void Widget::mousePressEvent(QMouseEvent *event)
{
p=event->pos();
}
实现效果