23062QTday3

完成文本编辑器的保存工作

cpp 复制代码
//保存文件
void Widget::on_savebtn_clicked()
{
    QString newfile=QFileDialog::getSaveFileName(this,
                                                 "保存文件",
                                                 "./",
                                                 "All(*.*);;Images(*.png *.xpm *.jpg);;Text files(*.txt);;");
    if(newfile.isNull())
    {
        QMessageBox::information(this,"提示","用户取消了保存文件");
        return;
    }
    QFile file(newfile);
    if (!file.open(QIODevice:: Truncate| QIODevice::ReadWrite| QIODevice::Text))
             return;
    QString msg=ui->textEdit->toPlainText();
    file.write(QByteArray(msg.toUtf8()));
    file.close();
}

运行结果:

头文件

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QTimerEvent>
#include<QTime>
#include <QTextToSpeech>          //文本转语音类
#include<QVoice>
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_closebtn_clicked();

private:
    Ui::Widget *ui;
    int timer_id;
    //定义一个播报员
    QTextToSpeech *speecher;
};
#endif // WIDGET_H

源文件:

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

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


void Widget::on_startbtn_clicked()
{
    timer_id=this->startTimer(1000);

}

void Widget::on_closebtn_clicked()
{
  //  this->killTimer(timer_id);
    speecher->stop();
    ui->lineEdit->clear();//清空闹钟定时
}

void Widget::timerEvent(QTimerEvent *e)
{
    //给播报员实例化空间
    speecher = new QTextToSpeech(this);
    if(e->timerId()==timer_id)
    {
        QTime sys_t=QTime::currentTime();
        QString t=sys_t.toString("hh:mm:ss");
        ui->label->setText(t);
        if(t==ui->lineEdit->text())
        speecher->say(ui->textEdit->toPlainText());
        speecher->rate();

    }
}

测试文件:

cpp 复制代码
#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}
相关推荐
Felix_One19 小时前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月9 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237179 天前
C语言-数组练习进阶
c语言·开发语言·算法