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

相关推荐
devilnumber2 小时前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
asdfg12589633 小时前
JavaBean是什么?怎么理解?有什么用途?
java·开发语言
dsyyyyy11014 小时前
JavaScript变量
开发语言·javascript·ecmascript
z落落5 小时前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
allway25 小时前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_462446235 小时前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了5 小时前
安装git bash选项推荐
开发语言·git·bash
ct9785 小时前
React 状态管理方案深度对比
开发语言·前端·react
数量技术宅6 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦6 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai