Qt事件处理机制
用qt实现简单闹钟
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include<QPushButton>
#include<QTextEdit>
#include<QLabel>
#include <QWidget>
#include<QMouseEvent>
#include<QPoint>
#include<QTime>
#include<QTimer>
#include<QFont>
#include<QLineEdit>
#include<QTextToSpeech>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
signals:
void voice();
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void time_slot();
void btn1_slot();
void btn2_slot();
void voice_slot();
private:
Ui::Widget *ui;
QLabel *lab1;
QPushButton *btn1;
QPushButton *btn2;
QTextEdit *edit1;
QLineEdit *ledit;
QTimer t1;
QFont font;
QTextToSpeech *speecher;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include<QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
lab1=new QLabel(this);
ledit=new QLineEdit(this);
btn1=new QPushButton(this);
btn2=new QPushButton(this);
edit1=new QTextEdit(this);
btn2->setEnabled(false);
speecher= new QTextToSpeech(this);
QTime systime=QTime::currentTime();
QString tm=systime.toString("hh:mm:ss");
this->lab1->setText(tm);
t1.start(1000);
connect(&t1,&QTimer::timeout,this,&Widget::time_slot);
connect(btn1,&QPushButton::clicked,this,&Widget::btn1_slot);
connect(btn2,&QPushButton::clicked,this,&Widget::btn2_slot);
connect(this,&Widget::voice,this,&Widget::voice_slot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::time_slot(){
lab1->move(80,30);
lab1->resize(200,50);
font.setPointSize(20);
QTime systime=QTime::currentTime();
QString tm=systime.toString("hh:mm:ss");
this->lab1->setText(tm);
lab1->setFont(font);
lab1->setAlignment(Qt::AlignCenter);
ledit->move(lab1->width()+lab1->x()+30,30);
ledit->resize(300,40);
ledit->setPlaceholderText("请输入xx时xx分xx秒");
btn1->move(ledit->x(),ledit->y()+ledit->height()+10);
btn1->setText("开始");
btn1->resize(80,40);
btn2->move(btn1->width()+btn1->x()+30,btn1->y());
btn2->resize(btn1->size());
btn2->setText(("结束"));
edit1->move(80,btn1->y()+btn1->height()+10);
edit1->resize(600,400);
QString tms=lab1->text();
QString msg=ledit->text();
if(tms==msg){
emit voice();
}
}
void Widget::voice_slot(){
QString msg1=edit1->toPlainText();
speecher->say(msg1.toUtf8());
}
void Widget::btn1_slot(){
btn1->setEnabled(false);
edit1->setEnabled(false);
ledit->setEnabled(false);
btn2->setEnabled(true);
}
void Widget::btn2_slot(){
btn1->setEnabled(true);
edit1->setEnabled(true);
ledit->setEnabled(true);
btn2->setEnabled(false);
}