QT读写文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

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

//字体按钮对应槽函数
void MainWindow::on_btn_front1_clicked()
{
    bool ok;      //是否选中字体
    //调出字体对话框
    QFont f =QFontDialog::getFont(&ok,QFont("隶书", 10, 5, true), this, "字体");//初始字体

    //将选择的字体设置到文本中
    if(ok)
    {
        //ui->textEdit1->setFont(f);//所有字体
        ui->textEdit1->setCurrentFont(f);//选中字体
    }

}
//颜色对应的槽函数
void MainWindow::on_btn_color2_clicked()
{
    //rgb
    QColor c = QColorDialog::getColor(QColor(35, 203,190), this, "颜色");
    //判断合法性
    if(c.isValid())
    {
      //  ui->textEdit1->setTextColor(c);//字体颜色
        ui->textEdit1->setTextBackgroundColor(c);//背景色
    }
}



void MainWindow::on_btn_open1_clicked()
{
    //1、找到要打开的路径
    QString filename = QFileDialog::getOpenFileName(
                this,          //父组件
                "选择",         //窗口名
                "./",           //起始路径
                "Txt(*.txt);;c程序(*.c);;C++(*.cpp);;*(*.*)");//;;间隔多种类型
    //2、文件操作使用QFILE获取
    QFile f(filename);

    //3、打开文件
    if(!f.open(QFile::ReadWrite))
    {
        return;
    }
    //4、读取内容
    //f.readAll();
    QByteArray msg = f.readAll();
    //5、将读取的文件放到ui

    ui->textEdit1->setText(msg);
    f.close();



}
//保存
void MainWindow::on_btn_save4_clicked()
{
    //1、保存的路径
    QString filename = QFileDialog::getSaveFileName(
                this,          //父组件
                "选择",         //窗口名
                "./",           //起始路径
                "Txt(*.txt);;c程序(*.c);;C++(*.cpp);;*(*.*)");//;;间隔多种类型


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


          textStream << str;
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值