目的:利用QT实现文本编辑器的打开文件,保存文件,修改字体,修改内容颜色等功能
头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QFont>
#include <QFontDialog>
#include <QDebug>
#include <QColor>
#include <QColorDialog>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_fontbut_clicked();
void on_colorbut_clicked();
void on_pushButton_2_clicked();
void on_pushButton_clicked();
private:
Ui::Widget *ui;
};
#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_fontbut_clicked()
{
bool ok;
QFont font=QFontDialog::getFont(&ok,QFont("宋体",12),this,"font");
if(ok == true)
{
qDebug()<<"你选中了怂体";
ui->textEdit->setFont(font);
}
else
{
qDebug()<<"您没没选中字体";
}
}
void Widget::on_colorbut_clicked()
{
QColor color=QColorDialog::getColor(Qt::white,this,"color");
ui->textEdit->setTextColor(color);
}
//打开文件按钮对应的槽函数
void Widget::on_pushButton_clicked()
{
QString filename = QFileDialog::getOpenFileName(this,"open file","./","Txt(*.txt)");
QFile file(filename);
if(file.open(QFile::ReadWrite))
{
QByteArray msg= file.readAll();
ui->textEdit->setText(QString::fromLocal8Bit(msg));
}
else
{
QMessageBox::information(this,"","文件打开失败");
}
}
//保存文件按钮对应的槽函数
void Widget::on_pushButton_2_clicked()
{
QString filename = QFileDialog::getSaveFileName(this, "保存文件","./","Txt(*.txt)");
QFile file(filename);
if(file.open(QFile::ReadWrite)){
QByteArray msg = ui->textEdit->toPlainText().toLocal8Bit();
file.write(msg);
}
else{
QMessageBox::information(this,"","文件保存失败");
}
}