12.12 Qt中的事件机制

2023-12-13 06:09:59

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#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) override;

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    int id; //定时器返回的标志
    int sid;
    QTextToSpeech *speecher;
};
#endif // WIDGET_H

main.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
?

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    speecher = new QTextToSpeech;
    id=startTimer(1000);
}

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

void Widget::timerEvent(QTimerEvent *e)
{
    if(e->timerId()==id)
    {
        //获取系统时间
        QTime sys_time = QTime::currentTime();
        QString s = sys_time.toString("hh.mm.ss");
        ui->systemtimelabel->setText(s);

    }
    if(e->timerId()==sid)
    {
        //判断系统时间和闹钟时间是否一致
        if(ui->systemtimelabel->text()==ui->lineEdit->text())
        {
            //播报
            int i=0;
            while(i<5)
            {
                speecher->setVoice(QVoice());
                speecher->say(ui->label->text());
                i++;
            }
        }
    }
}


void Widget::on_pushButton_clicked()
{
    if(ui->pushButton->text()=="启动")
    {
        sid = startTimer(1000);
        ui->pushButton->setText("关闭");

    }
    else
    {
        killTimer(sid);
        ui->pushButton->setText("启动");
    }
}


文章来源:https://blog.csdn.net/qq_62936323/article/details/134956796
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。