版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/wangxiaobei2017/article/details/78075558
打開和保存文件時調用的對話框,主要利用QFileDialog類下的靜態成員getOpenFileName()和getSaveFileName()。
// 做一個簡單的文本編輯器 使其具有打開文件和保存的功能
// 打開:讀取文件並顯示 保存:輸入一個新文件並保存
#include "Qt7_2A.h"
#include<QFileDialog>
#include<QDebug>
#include"GBK.h"
Qt7_2A::Qt7_2A(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//建立兩個按鈕的信號與槽的連接
connect(ui.btnOpen,SIGNAL(clicked()),this,SLOT(OnbtnOpen()));
connect(ui.btnSave, SIGNAL(clicked()), this, SLOT(OnbtnSave()));
}
int Qt7_2A::OnbtnOpen() // “打開”按鈕的處理函數
{
// 當用戶選擇打開按鈕後,通過QFileDialog類下的靜態成員getOpenFileName()函數進行文件選擇
// getOpenFileName()兩個參數,一個表示父類 一個表示標題
QString filepath = QFileDialog::getOpenFileName(this, GBK::ToUnicode("選擇文件"));
//
if (filepath.length() > 0)
{
qDebug() << filepath; // 顯示文件路徑
string gbk_name = GBK::FromUnicode(filepath);
// 打開文件,讀取內容
FILE* fp = fopen(gbk_name.c_str(),"rb");
// 獲得文件大小
fseek(fp, 0, SEEK_END);
int filesize = ftell(fp);
// 讀取內容
fseek(fp,0,SEEK_SET);
char* buf = new char[filesize + 1];
int n = fread(buf,1,filesize,fp);
if (n > 0)
{
buf[n] = 0;
//顯示到界面文本框中
ui.plainTextEdit->setPlainText(GBK::ToUnicode(buf));
}
delete[] buf; // 釋放內存
fclose(fp);
}
return 0;
}
int Qt7_2A::OnbtnSave()//“保存”按鈕的處理函數
{
// 保存一個文本文件 和打開類似
QString filepath = QFileDialog::getSaveFileName(this, GBK::ToUnicode("保存文件"));
//
if (filepath.length() > 0)
{
// 首先獲得文本框內的文本信息
QString text = ui.plainTextEdit->toPlainText();
string gbk_text = GBK::FromUnicode(text);// 轉換成GBK
string gbk_filename = GBK::FromUnicode(filepath);
// 打開文件
FILE* fp = fopen(gbk_filename.c_str(), "wb");
fwrite(gbk_text.c_str(),1,gbk_text.length(),fp);
fclose(fp);//關閉文件
}
return 0;
}