当前位置:网站首页>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

【C语言】动态内存管理

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

【搜索】双向广搜 + A*

QT 菜单栏、工具栏和状态栏

STL upper series - detailed explanation of list container

R-score reproduction R-Precision evaluation index quantitative text generation image r-score quantitative experiment whole process reproduction (R-Precision) quantitative evaluation experiment step on

kali系统arp介绍(断网嗅探密码抓包)

ps样式如何导入?Photoshop样式导入教程

Idea 如何新建一个groovy的项目(图文详细解释)
随机推荐
Affine transformation module and conditional batch Standardization (CBN) of detailed text generated images
kali系统arp介绍(断网嗅探密码抓包)
标准对话框 QMessageBox
项目对接支付宝支付,内网穿透实现监听支付宝的支付成功异步回调通知
背包问题dp
勤于奋聊聊现在还有哪些副业可以做
Why is select not recommended*
Knapsack problem DP
【无标题】按照一定的条件,对 i 进行循环累加。条件通常为循环数组的长度,当超过长度就停止循环。因为对象无法判断长度,所以通常搭配 Object.keys() 使用。\nforEach 一般认为是 普
C中文件I/O的使用
Comprehensive experiment of static routing
static和final关键字 学习 demo练习
再一个技巧,每月稳赚3万+
What if Photoshop prompts that the temporary storage disk is full? How to solve the problem that PS temporary storage disk is full?
MySQL storage engine and its differences
How to copy Photoshop layers to other documents
CDH集群集成外部Flink(改进版-与时俱进)
There is no need to install CUDA and cudnn manually. You can install tensorflow GPU through a one-line program. Take tensorflow gpu2.0.0, cuda10.0, cudnn7.6.5 as examples
ps怎么导入lut预设?Photoshop导入lut调色预设教程
关于gorm的BeforeDelete钩子方法不生效的问题