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:

运行结果:

相关推荐
用户8055336980317 小时前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner18 小时前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner9 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner10 天前
DicomViewer (目录调整) 2
qt
xcyxiner11 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00612 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术12 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript