十六、【文本编辑器(二)】文件操作功能
目录
一、新建文件
(1)在imgProcessor.h添加槽函数声明
protected slots:
void ShowNewFile();
(2) 在imgProcessor.cpp添加函数关联和函数实现
NewFileAction =new QAction(QIcon("new.png"),tr("新建"),this);
NewFileAction->setShortcut(tr("Ctrl+N"));
NewFileAction->setStatusTip(tr("新建一个文件"));
connect(NewFileAction,SIGNAL(triggered()),this,SLOT(ShowNewFile()));
void ImgProcessor::ShowNewFile()
{
ImgProcessor *newImgProcessor =new ImgProcessor;
newImgProcessor->show();
}
(3)点击“文件”->“新建”命令或单击工具栏的新建按钮。
二、打开文件
利用标准文件对话框 QFileDialog 打开一个已经存在的文件。若当前中央窗体中已有打开的文件,则在一个新的窗口中打开选定的文件;若当前中央窗体是空白的,则在当前窗体中打开。
(1) 在 “imgprocessor.h” 头文件中添加 “protected slots:”变量:
void ShowOpenFile();
(2) 在 createActions() 函数的“"打开"动作”最后添加事件关联:
connect(openFileAction,SIGNAL(triggered()),this,SLOT(ShowOpenFile()));
(3) 实现打开文件功能的函数 ShowOpenFileo如下:
void ImgProcessor::ShowOpenFile()
{
//获取用户选择打开的文件
fileName =QFileDialog::getOpenFileName(this,"打开");
if(!fileName.isEmpty())
{
//获取文档对象,判断当前是否具有打开的文件
if(showWidget->text->document()->isEmpty())
{
//加载文件
loadFile(fileName);
}
else
{
//如果已经打开一个文件,就重新创建一个文本编辑器
ImgProcessor *newImgProcessor =new ImgProcessor;
newImgProcessor->show();
newImgProcessor->loadFile(fileName);
}
}
}
void ImgProcessor::loadFile(QString filename)
{
printf("file name:%s\n",filename.data());
QFile file(filename);
if(file.open(QIODevice::ReadOnly|QIODevice::Text))
{
//将打开的文件关联到QTextStream
QTextStream textStream(&file);
textStream.setCodec("UTF-8"); //设置编码格式
while(!textStream.atEnd())
{
showWidget->text->append(textStream.readLine());
printf("read line\n");
}
printf("end\n");
}
}
解析:
1、QTextEdit
在Qt框架中,QTextEdit是一个用于显示和编辑文本内容的控件。document()函数用于获取QTextEdit控件中的文档对象,文档对象包含了文本内容以及格式信息。通过文档对象,你可以对文本内容进行操作,比如插入文本、设置格式等。
2、QString QFileDialog::getOpenFileName
QString QFileDialog::getOpenFileName
(
QWidget* parent=0,
const QString & caption=QString(),
const QString & dir=QString(),
const QString & filter=QString(),
QString * selectedFilter=QString(),
Options options=0
);
- QWidget* parent=0:定义标准文件对话框的父窗口。
- const QString & caption=QString( ):定义标准文件对话框的标题名。
- const QString & dir=QString( ):指定了默认的目录,若此参数带有文件名,则文件将是默认选中的文件。
- const QString & filter=QString( ):此参数对文件类型进行过滤,只有与过滤器匹配的文件类型才显示,可以同时指定多种过滤方式供用户选择,多种过滤器之间用隔开。
- QString * selectedFilter=O:用户选择的过滤器通过此参数返回。
3、读取文件内容时,如果不需要额外的操作还可以使用下述代码
QFile file("path/to/your/file.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QByteArray content = file.readAll();
file.close();
QString text(content);
}
(5)点击“文件”->“打开”或单击工具栏的打开按钮,选择文件。效果如下:
原文地址:https://blog.csdn.net/qq_45790916/article/details/139250511
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!