完善文本编辑器

1.mainwindow.h文件

#ifndef MAINWINDOW_H#define MAINWINDOW_H#include #include #include #include #include #include #include #include #include #include #include #include #include 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()<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()<textEdit->toPlainText();QString msg_2="\n";QString msg=msg_2+msg_1;//5.文件读写file.write(msg.toLocal8Bit());//6.关闭文件file.close();QMessageBox::information(this,"提示","文件保存成功");}

打开功能展示

保存功能展示