04/27课后作业(Qt)

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("文件管理");
}

Widget::~Widget()
{
    delete ui;
}

//字体按钮对应的槽函数
void Widget::on_fontBtn_clicked()
{
    bool ok;            //返回是否选中字体
    QFont f = QFontDialog::getFont(&ok,QFont("隶书",20,5,true),this,"字体");
    //功能:调出系统字体对话框  1.返回选中字体状态  2.初始字体  3.父组件   4.对话框标题

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

}

//颜色按钮对应的槽函数
void Widget::on_colorBtn_clicked()
{
    //调取颜色对话框
    QColor c = QColorDialog::getColor(QColor(172,196,237),this,"颜色");

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

}

//打开文件按钮对应的槽函数
void Widget::on_openfileBtn_clicked()
{
    //    QString filename = QFileDialog::getOpenFileName(this,"选择文件", "./../../", "Image Files (*.txt *.png *.jpg *.bmp)");
    QString filename = QFileDialog::getOpenFileName(this,"选择文件", "./../../", "All(*.*);;Txt(*.txt);;c程序(*.c);;Png(*.png);;Jpg(*.jpg);;Bmp(*.bmp)");
    //1.父组件      2.窗口名   3.路径    4.文件类型
    qDebug() << filename;

    //使用QFILE类实例化一个对象,可以用获取的路径名进行构造
    QFile f(filename);
    //打开文件(读写)
    if(!f.open(QFile::ReadWrite)){
        //        QMessageBox::warning(this,tr("提示"),tr("文件不存在"));
        return;
    }
    //读取文件内容,将文件内容放到ui界面
    QByteArray msg = f.readAll();           //将文件中内容全部读出来 msg以字节为单位的起始地址

    //将读取到的内容放到ui界面
    ui->msgEdit->setText(msg);

    //关闭文件
    f.close();

}

//保存文件按钮对应的槽函数
void Widget::on_savefileBtn_clicked()
{
    QString filename = QFileDialog::getSaveFileName(this,"文件保存为","./../../","Txt(*.txt);;c程序(*.c);;Png(*.png);;Jpg(*.jpg);;Bmp(*.bmp);;All(*.*)");
    qDebug() << filename;

    QFile f(filename);
    if(!f.open(QFile::WriteOnly)){
        return;
    }
    else
    {
        QTextStream textStream(&f);
        textStream.setCodec("UTF-8");
        QString str = ui->msgEdit->toPlainText();
        //        qDebug() << str;

        textStream << str;
        QMessageBox::information(this,tr("提示"),tr("保存文件成功"));

        f.close();
    }
}

1.打开文件

 2.编辑

 3.保存

 4.再次打开

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值