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:

运行结果:

相关推荐
apcipot_rain10 小时前
C++转Java日记(06)
java·开发语言
SomeOtherTime16 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood17 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青17 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
饮水桶_T21 小时前
JAVA IO流笔记
开发语言·数据结构·算法
Felven1 天前
C. Brr Brrr Patapim
c语言·开发语言
路溪非溪1 天前
python标准库使用总结
开发语言·python
SomeOtherTime1 天前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
zh_xuan1 天前
kotlin常见面试题
开发语言·kotlin·面试题
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试