Qt_day5:2024/3/26

作业:实现闹钟

代码:

头文件:

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimerEvent> //定时器事件
#include <QTime> //时间类
#include <QtTextToSpeech> //文本转语音类
#include <QMouseEvent> //鼠标事件类
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    //声明重写定时器事件函数
    void timerEvent(QTimerEvent *e);


private slots:
    void on_startbtn_clicked();


private:
    Ui::Widget *ui;
    int id;//定时器id
    int id2;

    //实例化一个语言播报员
    QTextToSpeech *speecher;
};
#endif // WIDGET_H

源文件:

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , speecher(new QTextToSpeech(this)) //给播报员申请空间
{
    ui->setupUi(this);

    //启动定时器
    id = startTimer(0);


}

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

void Widget::timerEvent(QTimerEvent *e)
{
    if(e->timerId() == id)
    {
        //获取系统时间
        QTime sys_time = QTime::currentTime();

        //将系统时间转换为字符串
        QString s = sys_time.toString("hh:mm:ss");

        //将系统时间在ui界面显示
        ui->timelab->setText(s);
        //居中显示
        ui->timelab->setAlignment(Qt::AlignCenter);
    }
    else if(e->timerId() == id2)
    {
        //当设置的时间到达后,开始播报
        if(ui->timeredit->text() == ui->timelab->text())
        {
            int num = 5;
            while(num--)
            {
                speecher->say(ui->testlab->text());
            }
            //关闭定时器
            killTimer(id2);
        }

    }
}

//按下启动按钮
void Widget::on_startbtn_clicked()
{

    //按下启动按钮后,开启定时器2
    id2 = startTimer(0);

}

效果:

1711457275783729381

相关推荐
stanleyrain4 分钟前
c++指针问题
开发语言·c++
北极糊的狐10 分钟前
stream.findFirst().get() 报错 NoSuchElementException
开发语言·python
如意.75912 分钟前
【C++】从 I0 库到缓冲区,一篇吃透输入输出
开发语言·c++
JIngJaneIL14 分钟前
基于Java旅游信息推荐系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·旅游
黑客思维者15 分钟前
Python数据清洗实战:去重/标准化
开发语言·python·数据清洗·数据标准化
CryptoRzz16 分钟前
对接印度股票市场数据 (India api) 实时k线图表
java·开发语言·python·区块链·maven
曹牧25 分钟前
C#和Java的String
开发语言·c#
神仙别闹31 分钟前
基于QT(C++)实现宠物小精灵对战游戏
c++·qt·宠物
CoderYanger35 分钟前
A.每日一题——1925. 统计平方和三元组的数目
java·开发语言·数据结构·算法·leetcode·哈希算法
徐同保37 分钟前
n8n项目编译时取消类型检测,提交代码时取消校验
开发语言·前端·javascript