2.23 Qt day4 事件机制+定时器事件+键盘事件+鼠标事件

思维导图:

做一个闹钟,在行编辑器里输入定闹钟的时间,时间到了就语音播报文本里的内容,播报五次

widget.h:

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QDebug>//输出类
#include<QTimerEvent>//定时器事件类
#include<QTime>//时间类
#include<QTextToSpeech> //语音播报类

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_btn_clicked();

private:
    Ui::Widget *ui;
    int id1,id2;//定时器的id
    QString s;
    //实例化一个语音播报者
    QTextToSpeech *speecher;
};
#endif // WIDGET_H

main.cpp:

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

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

widget.cpp:

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    id1=startTimer(1000);//启动定时器
    //给语音播报者实例化空间
    speecher=new QTextToSpeech(this);
    ui->textLab->setAlignment(Qt::AlignCenter);
}

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

//当定时器超时时自动执行的函数
void Widget::timerEvent(QTimerEvent *e)
{
    if(e->timerId()==id1)
    {
        //获取当前系统时间
        QTime sys_time=QTime::currentTime();
        //类型转化
        s=sys_time.toString("hh:mm:ss");
        //放入timeLab中
        ui->timeLab->setText(s);
        //居中显示
        ui->timeLab->setAlignment(Qt::AlignCenter);
    }
    else if(e->timerId()==id2)
    {
        if(ui->setTimeEdit->text()==s&&ui->btn->text()=="关闭闹钟")
        {
            for(int i=0;i<5;++i)
            {
                //每播报一次打印出一次文本
                qDebug() << ui->textLab->text();
                speecher->say(ui->textLab->text());
            }
        }
    }
}
void Widget::on_btn_clicked()
{
    if(ui->btn->text()=="启动闹钟")
    {
        //将按钮上的文本设置成"关闭闹钟"
        ui->btn->setText("关闭闹钟");
        //启动定时器id2
        id2=startTimer(1000);
    }
    else
    {
        //将按钮上的文本设置成"启动闹钟"
        ui->btn->setText("启动闹钟");
    }
}

widget.ui:

运行结果:

相关推荐
李燚43 分钟前
Go 项目怎么组织:DDD 4 层 vs MVC vs 脚本式
开发语言·golang·mvc·ddd·agent框架·eino
2zcode1 小时前
免费开源项目文档:基于MATLAB图像处理的啤酒瓶口缺陷检测系统设计与实现
开发语言·图像处理·matlab
人工智能时代 准备好了吗2 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
LONGZETECH2 小时前
新能源汽车动力电池检测仿真教学系统:C/S 分层架构与数字化实训落地全解析
大数据·c语言·开发语言·人工智能·架构·系统架构·汽车
郝学胜-神的一滴2 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
Metaphor6922 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
言乐63 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
cui_ruicheng3 小时前
Python从入门到实战(六):非序列容器
开发语言·python
西西学代码3 小时前
Flutter---底部导航栏(2)
开发语言·javascript·flutter
legendary_1633 小时前
SINK芯片:Type-C统一供电时代的小家电核心方案
c语言·开发语言·人工智能·智能手机