完善文本编辑器
1.mainwindow.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QDebug>
#include <QIcon>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QMessageBox>#include <QFontDialog>
#include <QFont>
#include <QColorDialog>
#include <QColor>
#include <QFileDialog>
#include <QFile>namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_fontBtn_clicked();void on_colorBtn_clicked();void on_openBtn_clicked();void on_saveBtn_clicked();private:Ui::MainWindow *ui;
};#endif // MAINWINDOW_H
2.mainwindow.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_fontBtn_clicked()
{//字体bool ok;QFont f=QFontDialog::getFont(&ok,QFont("宋体",10,4,false),this,"选择字体");if(ok){ui->textEdit->setCurrentFont(f);}else{QMessageBox::information(this,"提示","用户没有选择字体");}
}void MainWindow::on_colorBtn_clicked()
{QColor c= QColorDialog::getColor(QColor(100,100,100),this,"选择字体颜色");if(c.isValid()){ui->textEdit->setTextColor(c);}else {QMessageBox::information(this,"提示","用户没有选择字体颜色");}QColor b= QColorDialog::getColor(QColor(100,50,30),this,"选择字体背景颜色");if(b.isValid()){ui->textEdit->setTextBackgroundColor(b);}else {QMessageBox::information(this,"提示","用户没有选择字体背景颜色");}
}void MainWindow::on_openBtn_clicked()
{QString filename=QFileDialog::getOpenFileName(this,"选择文件","./","所有文件(*.*);;头文件(*.h);;图片(*.png *.jpg *.xpm);;文本(*.txt)");qDebug()<<filename;//1.实例化文件对象QFile file(filename);//2.判断文件是否存在if(!file.exists()){QMessageBox::information(this,"提示","文件不存在");return;}//3.打开文件if(!file.open(QIODevice::ReadWrite)){QMessageBox::information(this,"错误","文件打开失败");}//4.文件读写QByteArray msg=file.readAll();//5.关闭文件file.close();//将读取下来的数据展示到UI界面的文本框上
// ui->textEdit->setText(QString::fromLocal8Bit(msg));ui->textEdit->setText(QString::fromUtf8(msg));}void MainWindow::on_saveBtn_clicked()
{QString filename=QFileDialog::getSaveFileName(this,"选择文件","./","所有文件(*.*);;头文件(*.h);;图片(*.png *.jpg *.xpm);;文本(*.txt)");qDebug()<<filename;//1.实例化文件对象QFile file(filename);//2.判断文件是否存在if(!file.exists()){QMessageBox::information(this,"提示","文件不存在");return;}//3.打开文件if(!file.open(QIODevice::Append)){QMessageBox::information(this,"错误","文件打开失败");}//4.获取UI界面的文本框上的数据QString msg_1=ui->textEdit->toPlainText();QString msg_2="\n";QString msg=msg_2+msg_1;//5.文件读写file.write(msg.toLocal8Bit());//6.关闭文件file.close();QMessageBox::information(this,"提示","文件保存成功");
}
打开功能展示
保存功能展示