QT事件处理

设计一个闹钟,定时播报内容。

QT事件处理_第1张图片

 

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 
#include 
#include 
#include 
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    int t;
    int flag;
    QTextToSpeech* speecher;
private slots:
    void on_beginbtn_clicked();

    void on_closebtn_clicked();

    void timerEvent(QTimerEvent *tm);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("闹钟");
    this->setWindowIcon(QIcon("C:\\Users\\huahua\\Documents\\C++\\QTtxt\\Qtapp\\02demo\\alarm.png"));
    t =this->startTimer(1000);
    QDateTime sys_time = QDateTime::currentDateTime();
    ui->label->setText(sys_time.toString("yyyy-MM-dd hh:mm:ss"));
    ui->label->setAlignment(Qt::AlignCenter |Qt::AlignVCenter);
    ui->label->setFont(QFont("Arial",15));
    ui->closebtn->setEnabled(false);
    speecher = new QTextToSpeech(this);
}

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

void MainWindow::on_beginbtn_clicked()
{
    flag = 1;
    if(ui->lineEdit->text()==nullptr) {
        QMessageBox::information(this,"错误","未定时");
        return;
    }
    if(ui->textEdit->toPlainText()==nullptr) {
        QMessageBox::information(this,"错误","未输入播报信息");
        return;
    }
    ui->lineEdit->setEnabled(false);
    ui->textEdit->setEnabled(false);
    ui->beginbtn->setEnabled(false);
    ui->closebtn->setEnabled(true);
}

void MainWindow::on_closebtn_clicked()
{
    flag=0;
    ui->lineEdit->setEnabled(true);
    ui->textEdit->setEnabled(true);
    ui->beginbtn->setEnabled(true);
    ui->closebtn->setEnabled(false);
}

void MainWindow::timerEvent(QTimerEvent *tm)
{
    if(tm->timerId()==t) {
        QDateTime sys_time = QDateTime::currentDateTime();
        ui->label->setText(sys_time.toString("yyyy-MM-dd hh:mm:ss"));
        if(flag==1 && ui->label->text()==ui->lineEdit->text()) {
            speecher->say(ui->textEdit->toPlainText());
            qDebug()<<"播报成功";
            flag=0;
            ui->lineEdit->setEnabled(true);
            ui->textEdit->setEnabled(true);
            ui->beginbtn->setEnabled(true);
            ui->closebtn->setEnabled(false);
        }
    }
}

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