QT -Day3:

手动编写文本编辑器的功能:

#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_fontBtn_clicked()
{
    bool ok;   //返回是否选择
    //调出系统的字体对话框
    QFont f= QFontDialog::getFont(&ok,QFont("宋体",10,6,true),this,"字体");
    //功能:  调出系统的字体对话框
    //参数1: 返回  选中字体状态
    //参数2: 初试字体
    //参数3: 父组件
    //参数4:  对话框标题

    //将选中的字体设置到文本编辑器中
    if(ok)
    {
        //ui->msgEdit->setFont(f);       //将全部字体进行设置
        ui->msgEdit->setCurrentFont(f);  //设置当前字体
    }
}

//颜色按钮对应的槽函数
void Widget::on_colorBtn_clicked()
{
    //调取颜色对话框,选中颜色
    QColor c = QColorDialog::getColor(QColor(160,0,0),this,"颜色");
    //QColor c = QColorDialog::getColor(QColor(35,203,190),this,"颜色");

    //判断颜色是否合法
    if(c.isValid())
    {
        //将该颜色选择到当前文本
        ui->msgEdit->setTextColor(c);  //设置字体颜色前景色
        // ui->msgEdit->setTextBackgroundColor(c);  //设置背景色
    }
}

//打开文件
void Widget::on_openFileBtn_clicked()
{
    //1. 找到要打开文件的路径
    QString fileName = QFileDialog::getOpenFileName(
                this,           //父组件
                "选择文件",      //窗口名
                "./",          // 起始名
                "Txt(*.txt);;c程序(*.c);;C++程序(*.cpp);;all(*.*)"); //过滤器

    // qDebug()<<fileName;   //查看路径
    //2.使用QFile类实例化一个对象,可以用获取的路径名进行构造
    QFile f (fileName);

    //3. 打开文件
    if(!f.open(QFile::ReadWrite)) //以读写形式打开文件
    {
        return;
    }

    // 4. 读取文件内容,将文件内容放到ui界面
    QByteArray msg= f.readAll();   //将文件的内容全部读取出来
    //5. 将读取出来的内容放到ui界面
    ui->msgEdit->setText(msg);
    //6.关闭文件
    f.close();

}

//保存按钮对应的槽函数
void Widget::on_saveFileBtn_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this,
                                                    "选择文件",
                                                    "./",
                                                    "Txt(*.txt);;c程序(*.c);;C++程序(*.cpp);;all(*.*)");
    qDebug()<<fileName;  //获取文件路径

    //文件操作
    //1、实例化一个文件对象
    QFile f(fileName);

    //2、判断该文件是否存在
    if(!f.exists())
    {
        QMessageBox::information(this,"信息", "文件不存在");
        return;
    }

    //打开文件
    if(f.open(QFile::ReadWrite) == false)
    {
        QMessageBox::information(this,"信息", "文件打开失败");
    }

    //获取ui界面上的文本内容
    // QString msg = ui->textEdit->toPlainText();
    QString msg = ui->msgEdit->toPlainText();
    //将内容写入文件中
    f.write(msg.toLocal8Bit());
    //关闭文件
    f.close();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值