题目:手动完成编辑器功能
widget.cpp
//字体按钮对应的槽函数
void Widget::on_fontButton_clicked()
{
//返回是否选中字体
bool ok;
//调出系统的字体对话框
QFont f = QFontDialog::getFont(&ok, QFont("隶书", 10, 5, true), this, "字体");
//功能:调出系统字体的对话框
//参数1:返回字符选中字体状态
//参数2:初始化字体
//参数3:父组件
//参数5:对话框标题
//将选中的字体设置到文本编辑器中
if(ok)
{
//将全部字体进行设置
//ui ->msgEdit ->setFont(f);
//将选中的字体更改设置
ui ->msgEdit ->setCurrentFont(f);
}
}
//颜色按钮对应的槽函数
void Widget::on_colorButton_clicked()
{
//调取颜色对话框,选中颜色
QColor c = QColorDialog::getColor(QColor(35, 203, 190), this, "颜色");
//判断颜色是否合法
if(c.isValid())
{
//该颜色添加到当前选中文本
//设置颜色的前景色
//ui ->msgEdit ->setTextColor(c);
//设置当前选中颜色的背景色
ui ->msgEdit ->setTextBackgroundColor(c);
}
}
//打开文件对应的槽函数
void Widget::on_openButton_clicked()
{
//1.找到要打开的文件路径
QString fileName = QFileDialog::getOpenFileName(
this, //父组件
"选择", //窗口名
"./", //起始名
".txt(*.txt);;c程序(*.c);;C++程序(*.cpp);;all(*.*)"); //过滤器
//2.使用QFile类实例化一个对象,可以用获取的路径名进行构造
QFile f(fileName);
//3.打开文件
if(!f.open(QFile::ReadWrite)) //以读写形式打开文件
{
return;
}
//4.读取文件内容,将文件内容放到ui界面
QByteArray msg = f.readAll(); //将文件中的内容全部读取出来,msg是字节数组
//5.将读取出来的内容放到ui界面
ui ->msgEdit ->setText(msg);
//6.关闭文件
f.close();
}
//保存文件对应的槽函数
void Widget::on_saveButton_clicked()
{
//1.选择要保存的路径
QString fileName = QFileDialog::getSaveFileName(this,
"选择文件",
"./",
"all(*.*);;cpp(*.cpp);;image(*.png,*.jpg,*.jpg2)");
//2.使用QFile实例化一个对象,可以用获取的路径名进行构造
QFile s(fileName);
//3.打开文件,以读写的方式
if(!s.open(QFile::ReadWrite))
{
return;
}
//4.文件写到UI上,并读取UI上的内容
QString msg = ui ->msgEdit ->toPlainText();
//5.将内容写入文件
s.write(msg.toLocal8Bit());
//6.关闭文件
s.close();
}
widget.h
#include <QWidget>
#include <QFont> //字体类
#include <QFontDialog> //字体对话框类
#include <QColor> //颜色类
#include <QColorDialog> //颜色类对话框
#include <QFileDialog> //文件对话框类
#include <QFile> //文件类
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_fontButton_clicked();
void on_colorButton_clicked();
void on_openButton_clicked();
void on_saveButton_clicked();
结果:




这篇文章展示了如何在Qt环境中编写GUI应用,包括通过槽函数实现字体选择、颜色选择、文件打开和保存功能。用户可以点击按钮来改变文本编辑器的字体、颜色,以及加载和保存文本文件。
1736

被折叠的 条评论
为什么被折叠?



