qt 闹钟实现

实现一个闹钟  自定义时间 按下开始后 开始计时,结束计时会播报语音

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimer>
#include <QTimerEvent>
#include <QDateTime>
#include <QTime>
#include <QTextToSpeech>
#include <QString>
#include <QMessageBox>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

    //重写定时器事件处理函数
    void timerEvent(QTimerEvent *e) override;

private slots:
    void on_startbtn_clicked();
    void timeout_slot();

    void on_stopbtn_clicked();

private:
    Ui::Widget *ui;
    QTimer *obj_timer;
    QTime sys_time;
    //定义一个计时器的id
    int event_timer;
    QTextToSpeech *speech;
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    speech=new QTextToSpeech(this);
    ui->stopbtn->setEnabled(false);
    obj_timer=new QTimer(this);
    obj_timer->start(1000);
    //将定时器发射的timeout信号与自定义的槽函数进行连接
    connect(obj_timer,&QTimer::timeout,this,&Widget::timeout_slot);
    ui->te3->setText("今天辛苦啦!打工人~ 好好休息哦");

}

Widget::~Widget()
{
    delete ui;
}

void Widget::timerEvent(QTimerEvent *e)
{
    if(e->timerId()==event_timer)
    {
        if(ui->te2->toPlainText()==sys_time.toString("hh:mm:ss"))
        {
            speech->say("时间到了");
            ui->startbtn->setEnabled(true);
            ui->stopbtn->setEnabled(false);
            ui->te2->setEnabled(true); //设置时间可以被更改
           this->killTimer(event_timer); //关闭第二个的计时器
            ui->te3->clear();
            ui->te3->setText("来活了!");

        }
}
}

void Widget::on_startbtn_clicked()
{
    if(ui->startbtn->isEnabled())
   {
    ui->startbtn->setEnabled(false); //设置开始按钮 不可按
    ui->stopbtn->setEnabled(true);
    ui->te2->setEnabled(false); //设置时间不能更改
    event_timer=this->startTimer(1000);
    ui->te3->clear();
    ui->te3->setText("离你预定的时间很近咯!");
   }


}

void Widget::timeout_slot()
{
    ui->te1->setAlignment(Qt::AlignCenter);
    sys_time=QTime::currentTime();
    ui->te1->setText(sys_time.toString("hh:mm:ss"));

}

void Widget::on_stopbtn_clicked()
{
    QMessageBox::information(this,"停止对话框","计时停止");
    this->killTimer(event_timer); //关闭第二个的计时器
    ui->startbtn->setEnabled(true); //设置开始按钮 不可按
    ui->te2->setEnabled(true); //设置时间可以被更改
    ui->stopbtn->setEnabled(false);
    ui->te3->setText("好消息 事件已经被取消啦!可以多休息一会啦");

}

运行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值