12.12 Qt中的事件机制

12.12 Qt中的事件机制_第1张图片

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 

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 

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("启动");
    }
}

12.12 Qt中的事件机制_第2张图片

你可能感兴趣的:(qt,开发语言)