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:

运行结果:

相关推荐
isyangli_blog1 小时前
OpenDayLight (Carbon 版本) 启动与组件安装
开发语言·php
vb2008112 小时前
FastAPI APIRouter
开发语言·python
Benszen2 小时前
KVM虚拟化解决方案
开发语言·perl
会编程的土豆2 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
東雪木2 小时前
多线程与并发编程 专属复习笔记
java·开发语言·笔记·java面试
杨充2 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
噜噜噜阿鲁~2 小时前
python学习笔记 | 11.3、面向对象高级编程-多重继承
java·开发语言
basketball6162 小时前
Go 语言从入门到进阶:4. 数组和MAP使用方法总结
开发语言·后端·golang
春生野草3 小时前
反射、Tomcat执行
java·开发语言
雪的季节4 小时前
企业级 Qt 全功能项目
开发语言·数据库·qt