当前位置:网站首页>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 :
边栏推荐
- Sunset red warm tone tinting filter LUTS preset sunset LUTS 1
- UUID and indexing rules
- 二叉搜索树详讲
- Plato Farm有望通过Elephant Swap,进一步向外拓展生态
- Counting Nodes in a Binary Search Tree
- 文件对话框
- Final Cut Pro Chinese tutorial (1) basic understanding of Final Cut Pro
- .htaccess学习
- 柔性数组以及常见问题
- [search] flood fill and shortest path model
猜你喜欢
![[search] flood fill and shortest path model](/img/22/5240c9ff6ea3c7c1017e3e9a4a27cb.png)
[search] flood fill and shortest path model

Final Cut Pro Chinese tutorial (1) basic understanding of Final Cut Pro

背包问题dp

Dialog introduction

【C语言】动态内存管理

.htaccess学习
![[search] - multi source BFS + minimum step model](/img/42/11b5b89153ab48d837707988752268.png)
[search] - multi source BFS + minimum step model

Easily download data in power Bi reports with power auto

JS tips

C language - two dimensional array, pointer
随机推荐
Read write separation and master-slave synchronization
对话框简介
会议OA之我的审批
Photoshop提示暂存盘已满怎么办?ps暂存盘已满如何解决?
Comprehensive experiment of static routing
[search] two way search + A*
[C language] detailed explanation of user-defined types (structure + enumeration + Union)
使用Photoshop出现提示“脚本错误-50出现一般Photoshop错误“
缓存读写策略:CacheAside、Read/WriteThrough及WriteBack策略
集成开发环境Pycharm的安装及模板设置
[error reporting]: cannot read properties of undefined (reading 'prototype')
[search] connectivity model of DFS + search order
TCP's three handshakes and four waves
Complete Binary Tree
【搜索】双向广搜 + A*
Customize the viewport height, and use scrolling for extra parts
事件过滤器
vim的基本操作
使用ngrok做内网穿透
Sub database and sub table