完成文本编辑器的保存工作
//保存文件
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();
}
运行结果:
头文件
#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
源文件:
#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();
}
}
测试文件:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}