QT定时器简单应用

QT定时器简单应用_第1张图片

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#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 *event) override;
private slots:
    void on_initBtn_clicked();
    void on_stopBtn_clicked();
private:
    Ui::Widget *ui;
    int timer_id1;
    int timer_id2;
    QTextToSpeech* speecher;
};
#endif // WIDGET_H

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(this);
    speecher->setLocale(QLocale::Chinese);
    //设置窗口
    this->setFixedSize(400, 300);
    //设置时间便签
    ui->timeLab->move(40, 40);
    ui->timeLab->resize(140, 90);
    ui->timeLab->setAlignment(Qt::AlignCenter);
    QFont font("隶书", 16, 75);
    ui->timeLab->setFont(font);
    //设置时间行编辑器
    ui->timeLin->move(ui->timeLab->x()+180,ui->timeLab->y());
    ui->timeLin->resize(140, 40);
    //设置开始按钮
    ui->initBtn->move(ui->timeLin->x(), ui->timeLin->y()+50);
    ui->initBtn->resize(60, 40);
    ui->initBtn->setText("启动");
    //设置停止按钮
    ui->stopBtn->move(ui->initBtn->x()+80, ui->initBtn->y());
    ui->stopBtn->resize(60, 40);
    ui->stopBtn->setText("停止");
    //设置提醒文本编辑器
    ui->warnText->move(ui->timeLab->x(),ui->timeLab->y()+130);
    ui->warnText->resize(320, 90);
    ui->warnText->setText("荷尽已无擎雨盖\n\t菊残犹有傲霜枝");
    ui->warnText->setFont(font);
    ui->warnText->setAlignment(Qt::AlignCenter);
    //定时器1开始工作
    this->timer_id1 = startTimer(1000);
}

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

void Widget::timerEvent(QTimerEvent *event)
{
    QTime sys_t = QTime::currentTime();
    QString t = sys_t.toString("hh:mm:ss");
    if(event->timerId() == timer_id1)
    {
        ui->timeLab->setText(t);
    }else if(ui->timeLin->text() == t)
    {
        speecher->say(ui->warnText->toPlainText());
    }
}

void Widget::on_initBtn_clicked()
{
    this->timer_id2 = startTimer(1000);
}

void Widget::on_stopBtn_clicked()
{
    this->killTimer(timer_id2);
}

main.cpp

#include "widget.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

widget.ui

QT定时器简单应用_第2张图片

效果图 

QT定时器简单应用_第3张图片

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