当前位置:网站首页>File dialog box
File dialog box
2022-07-27 05:02:00 【PHP code】
In the previous chapter , We talked about Qt Standard dialog box QMessageBox Use . The so-called standard dialog box , In fact, it is an ordinary dialog box . therefore , We can also put QDialog Other features provided apply to this standard dialog . today , Let's move on to another standard dialog :QFileDialog, The file dialog box . In this section , We will try to write a simple text file editor , We will use QFileDialog To open a text file , And save the modified file to the hard disk . This is probably the first example with practical functions that we provide in this series .
First , We need to create a window with text editing function . To borrow from our previous program code , It should be easy to do :
openAction = new QAction(QIcon(":/images/file-open"), tr("&Open..."), this);
openAction->setShortcuts(QKeySequence::Open);
openAction->setStatusTip(tr("Open an existing file"));
saveAction = new QAction(QIcon(":/images/file-save"), tr("&Save..."), this);
saveAction->setShortcuts(QKeySequence::Save);
saveAction->setStatusTip(tr("Save a new file"));
QMenu *file = menuBar()->addMenu(tr("&File"));
file->addAction(openAction);
file->addAction(saveAction);
QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);
toolBar->addAction(saveAction);
textEdit = new QTextEdit(this);
setCentralWidget(textEdit);
We added two actions to the menu and toolbar : Open and save . Next is a QTextEdit class , This class is used to display rich text files . in other words , It's not just for displaying text , It can also show pictures 、 Forms, etc . however , Now we only use it to display plain text files .QMainWindow There is one setCentralWidget() function , You can use a component as the central component of the window , In the center of the window . obviously , In a text editor , The text editing area is the central component , So we will QTextEdit As such a component .
We use connect() function , For these two QAction Object to add a response action :
/// !!!Qt5
connect(openAction, &QAction::triggered, this, &MainWindow::openFile);
connect(saveAction, &QAction::triggered, this, &MainWindow::saveFile);
/// !!!Qt4
connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
None of this should be a problem . We should be able to clearly understand the meaning of these codes . Here's the main openFile() and saveFile() The code for these two functions :
void MainWindow::openFile()
{
QString path = QFileDialog::getOpenFileName(this,
tr("Open File"),
".",
tr("Text Files(*.txt)"));
if(!path.isEmpty()) {
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, tr("Read File"),
tr("Cannot open file:\n%1").arg(path));
return;
}
QTextStream in(&file);
textEdit->setText(in.readAll());
file.close();
} else {
QMessageBox::warning(this, tr("Path"),
tr("You did not select any file."));
}
}
void MainWindow::saveFile()
{
QString path = QFileDialog::getSaveFileName(this,
tr("Open File"),
".",
tr("Text Files(*.txt)"));
if(!path.isEmpty()) {
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, tr("Write File"),
tr("Cannot open file:\n%1").arg(path));
return;
}
QTextStream out(&file);
out << textEdit->toPlainText();
file.close();
} else {
QMessageBox::warning(this, tr("Path"),
tr("You did not select any file."));
}
}
stay openFile() Function , We use QFileDialog::getOpenFileName() To get the path of the file to be opened . This function has a long signature :
QString getOpenFileName(QWidget * parent = 0,
const QString & caption = QString(),
const QString & dir = QString(),
const QString & filter = QString(),
QString * selectedFilter = 0,
Options options = 0)
But pay attention to , All of its parameters are optional , So to a certain extent , This function is also simple . These six parameters are :
- parent: The parent window . We introduced ,Qt The standard dialog box provides static functions , Used to return a modal dialog ( To some extent, this is an embodiment of the appearance mode );
- caption: Dialog title ;
- dir: The default directory when the dialog box opens ,“.” Represents the program running directory ,“/” Represents the root directory of the current drive letter ( especially Windows platform ;Linux The platform, of course, is the root directory ), This parameter can also be platform related , such as “C:\” etc. ;
- filter: filter . We can browse many kinds of files by using the file dialog box , however , Most of the time we just want to open certain types of files . such as , The text editor wants to open a text file , The image browser wants to open the image file . Filters are used to filter specific suffixes . If we use “Image Files(.jpg .png)”, Only the suffix is jpg perhaps png The file of . If you need more than one filter , Use “;;” Division , such as “JPEG Files(.jpg);;PNG Files(.png)”;
- selectedFilter: The filter selected by default ;
- options: Some parameter settings of dialog box , For example, only display the folder and so on , It's going to be theta
enum QFileDialog::Option, Each option can use | The combination of operations .
QFileDialog::getOpenFileName() The return value is the selected file path . We assign it to path. By judgment path Is it empty , You can determine whether the user has selected a file . Only when the user selects a file , We just do the following . stay saveFile() Used in QFileDialog::getSaveFileName() It's the same thing . Using this static function , stay Windows、Mac OS The above are all direct calls to local dialog boxes , however Linux On the other hand, it's QFileDialog My own simulation . It suggests that , If you don't use these static functions , But directly QFileDialog Set it up , As we mentioned earlier QMessageBox The settings are the same , The resulting dialog box is likely to be inconsistent with the appearance of the system dialog box . This point needs to be noted .
First , We create a QFile object , Pass the file path selected by the user to this object . Then we need to open this file , It uses QFile::open(), Its parameter is the specified opening method , Here we use read-only mode and text mode to open this file ( Because we choose the suffix txt The file of , It can be considered as a text file . Of course , in application , Further judgment may be required ).QFile::open() If it is opened successfully, it returns true, Continue with the following operation : Use QTextStream::readAll() Read all contents of the file , Then assign it to QTextEdit Show it . Finally, don't forget to close the file . in addition ,saveFile() Functions are similar , Just the last step , We use << Redirect , take QTextEdit Output the contents of to a file . About file manipulation , We will introduce it further in the following chapters .
Here's a little bit of attention : Our code is just for demonstration , Many necessary operations have not been carried out . such as , We didn't check whether the actual type of this file is a text file . also , We used QTextStream::readAll() Read all contents of the file directly , If this file has 100M, The program will die immediately , These are all issues that must be considered in the actual procedure . However, these contents are beyond the introduction of this chapter , There will be no more details .
thus , Our code has been introduced , You can compile and run it soon :

The code of this chapter can be downloaded here :
边栏推荐
- C语言 通讯录管理系统(链表,手机号码分段存储,txt文件存取,完整源码)
- UUID and indexing rules
- HCIA static routing basic simulation experiment
- Basic configuration of static routing to achieve network wide accessibility
- Final Cut Pro中文教程 (1) 基础认识Final Cut Pro
- Digital integrated circuit: CMOS inverter (I) static characteristics
- Hiding skills of Photoshop clipping tool
- 如何重置Photoshop首选项?ps重置首选项的方法
- Dynamic routing configuration
- C中文件I/O的使用
猜你喜欢

老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破

How to import PS style? Photoshop style import tutorial

Review of various historical versions of Photoshop and system requirements

Affine transformation module and conditional batch Standardization (CBN) of detailed text generated images

项目对接支付宝支付,内网穿透实现监听支付宝的支付成功异步回调通知

The execution process of a select statement in MySQL

CDH集群集成外部Flink(改进版-与时俱进)

Final Cut Pro中文教程 (2) 素材窗口的认识

小程序项目如何创建

Hiding skills of Photoshop clipping tool
随机推荐
static和final关键字 学习 demo练习
日落红暖色调调色滤镜luts预设Sunset LUTs 1
Row, table, page, share, exclusive, pessimistic, optimistic, deadlock
【报错】Cannot read property ‘parseComponent‘ of undefined
自定义视口高度,多余的部分使用滚动
Final Cut Pro中文教程 (1) 基础认识Final Cut Pro
[search] connectivity model of DFS + search order
网络协议详解:IP
小程序项目如何创建
Simple static routing in ENSP
Reproduce ssa-gan using the nine day deep learning platform
接口和抽象类/方法学习 demo
JS tips
【C语言】动态内存管理
Digital integrated circuit: CMOS inverter (I) static characteristics
ps样式如何导入?Photoshop样式导入教程
How to create an applet project
2019 top tennis cup upload
Easily download data in power Bi reports with power auto
【搜索】Flood Fill 和 最短路模型