C++&QT day10

2> Complete the saving work of the text editor

3>

2:

//保存按钮对应槽函数
void Widget::on_saveBtn_clicked()
{
    QString Filename=QFileDialog::getSaveFileName(this,//父组件
                                                  "保存文件",
                                                  "./",//起始路径
                                                  "All(*.*)");
    //判断文件是否存在
    if(Filename.isNull())
    {
        QMessageBox::information(this,"提示","用户取消保存文件");
        return;
    }
    else
    {
       //qDebug()<<Filename;
       //文件操作
       //1、实例化一个文件对象
       QFile file(Filename);
       //2、打开文件
       //3、读写操作
       //1、实例化一个文件对象
       file.open(QIODevice::WriteOnly);//创建文件,且权限为只写
       QString msg = ui->textEdit->toPlainText();//获取编辑器的文本内容
       QByteArray saveName;
       saveName.append(msg);
       file.write(saveName);
       file.close();
       //4、关闭文件
       file.close();
    }
}

3:

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);
    timer_id=this->startTimer(5);

}
Widget::~Widget()
{
    delete ui;
    this->killTimer(timer_id);//关闭定时器
}

//启动按钮
void Widget::on_startBtn_clicked()
{
    flag=1;
    //功能:启动一个定时器
    //参数:超时时间,每隔给定时间后自动调用定时器事件处理函数
    //返回值:当前定时器的id号
}
//停止按钮
void Widget::on_stopBtn_clicked()
{
    speecher->stop();
    flag=0;
}
//计时器
void Widget::timerEvent(QTimerEvent *e)
{
    if(e->timerId()==timer_id)
    {
        QTime sys_t=QTime::currentTime();
        QString t = sys_t.toString("hh:mm:ss");
        ui->timelabel->setText(t);
    }
    if(flag==1)
    {
        if(ui->lineEdit->text()==ui->timelabel->text())
        {
            speecher->say(ui->textEdit->toPlainText());
        }
    }
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimerEvent>//定时器事件处理类
#include <QTime>//定时器类
#include <QtTextToSpeech>
#include <QString>
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_startBtn_clicked();

    void on_stopBtn_clicked();

private:
    Ui::Widget *ui;
    int timer_id;//定时器的id号
    QTextToSpeech *speecher;
    int flag=0;
};
#endif // WIDGET_H

widget.ui

mind Mapping:

Guess you like

Origin blog.csdn.net/m0_59031281/article/details/133046316