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:

运行结果:

相关推荐
风逸hhh1 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮1 小时前
Python训练第四十三天
开发语言·python
ascarl20102 小时前
准确--k8s cgroup问题排查
java·开发语言
fpcc3 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
莱茵菜苗3 小时前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长3 小时前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao3 小时前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码3 小时前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人3 小时前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
英英_4 小时前
视频爬虫的Python库
开发语言·python·音视频