手动编写文本编辑器的功能:
#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_fontBtn_clicked()
{
bool ok; //返回是否选择
//调出系统的字体对话框
QFont f= QFontDialog::getFont(&ok,QFont("宋体",10,6,true),this,"字体");
//功能: 调出系统的字体对话框
//参数1: 返回 选中字体状态
//参数2: 初试字体
//参数3: 父组件
//参数4: 对话框标题
//将选中的字体设置到文本编辑器中
if(ok)
{
//ui->msgEdit->setFont(f); //将全部字体进行设置
ui->msgEdit->setCurrentFont(f); //设置当前字体
}
}
//颜色按钮对应的槽函数
void Widget::on_colorBtn_clicked()
{
//调取颜色对话框,选中颜色
QColor c = QColorDialog::getColor(QColor(160,0,0),this,"颜色");
//QColor c = QColorDialog::getColor(QColor(35,203,190),this,"颜色");
//判断颜色是否合法
if(c.isValid())
{
//将该颜色选择到当前文本
ui->msgEdit->setTextColor(c); //设置字体颜色前景色
// ui->msgEdit->setTextBackgroundColor(c); //设置背景色
}
}
//打开文件
void Widget::on_openFileBtn_clicked()
{
//1. 找到要打开文件的路径
QString fileName = QFileDialog::getOpenFileName(
this, //父组件
"选择文件", //窗口名
"./", // 起始名
"Txt(*.txt);;c程序(*.c);;C++程序(*.cpp);;all(*.*)"); //过滤器
// qDebug()<<fileName; //查看路径
//2.使用QFile类实例化一个对象,可以用获取的路径名进行构造
QFile f (fileName);
//3. 打开文件
if(!f.open(QFile::ReadWrite)) //以读写形式打开文件
{
return;
}
// 4. 读取文件内容,将文件内容放到ui界面
QByteArray msg= f.readAll(); //将文件的内容全部读取出来
//5. 将读取出来的内容放到ui界面
ui->msgEdit->setText(msg);
//6.关闭文件
f.close();
}
//保存按钮对应的槽函数
void Widget::on_saveFileBtn_clicked()
{
QString fileName = QFileDialog::getSaveFileName(this,
"选择文件",
"./",
"Txt(*.txt);;c程序(*.c);;C++程序(*.cpp);;all(*.*)");
qDebug()<<fileName; //获取文件路径
//文件操作
//1、实例化一个文件对象
QFile f(fileName);
//2、判断该文件是否存在
if(!f.exists())
{
QMessageBox::information(this,"信息", "文件不存在");
return;
}
//打开文件
if(f.open(QFile::ReadWrite) == false)
{
QMessageBox::information(this,"信息", "文件打开失败");
}
//获取ui界面上的文本内容
// QString msg = ui->textEdit->toPlainText();
QString msg = ui->msgEdit->toPlainText();
//将内容写入文件中
f.write(msg.toLocal8Bit());
//关闭文件
f.close();
}