完善文本编辑器
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
namespace Ui {
class MainWindow;
}
class MainWindow : public QWidget
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void mainWindow_slot();
private slots:
void on_btnFont_clicked();
void on_btnColor_clicked();
void on_btnOpen_clicked();
void on_btnSave_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFontDialog>
#include <QMessageBox>
#include <QColorDialog>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mainWindow_slot()
{
show();
}
void MainWindow::on_btnFont_clicked()
{
bool ok;
QFont font = QFontDialog::getFont(&ok,QFont("宋体",12,2,false),this,"字体");
if(ok) {
this->ui->textEdit->setCurrentFont(font);
} else {
QMessageBox messageBox(QMessageBox::Information,"提示","用户没有选择字体",QMessageBox::Ok);
messageBox.exec();
}
}
void MainWindow::on_btnColor_clicked()
{
QColor color = QColorDialog::getColor(QColor(100,100,100),this,"颜色");
if(color.isValid()) {
this->ui->textEdit->setTextColor(color);
} else {
QMessageBox::information(this,"提示","用户没有选择颜色");
}
}
void MainWindow::on_btnOpen_clicked()
{
QString path= QFileDialog::getOpenFileName(this,"打开文件","./","文件(*.txt);;图片(*.png *.jpg *.bmp);;所有文件(*.*)");
QFile file(path);
if(!file.exists()) {
QMessageBox::information(this,"提示","打开的文件不存在");
return;
}
if(!file.open(QIODevice::ReadWrite)) {
QMessageBox::information(this,"提示","打开文件失败");
return;
}
QByteArray byteArr = file.readAll();
file.close();
ui->textEdit->setText(byteArr);
}
void MainWindow::on_btnSave_clicked()
{
QString path = QFileDialog::getSaveFileName(this,"保存","./","文件(*.txt);;图片(*.png *.jpg *.bmp);;所有文件(*.*)");
QFile file(path);
if(!file.open(QIODevice::Append)) {
QMessageBox::information(this,"提示","保存文件失败");
return;
}
QString text = ui->textEdit->toPlainText();
text.data();
int len = file.write(text.toLocal8Bit());
if(len>0) {
QMessageBox::information(this,"提示","保存文件成功");
}
file.close();
}