热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

10_文件对话框.md

文件对话框目录文件对话框QFileDialog::getOpenFileName()来获取需要打开的文件QStringgetOpenFileName(QWidget*parent0

文件对话框

目录



  • 文件对话框

QFileDialog::getOpenFileName()来获取需要打开的文件

QString getOpenFileName(QWidget * parent = 0,
const QString & caption = QString(),
const QString & dir = QString(),
const QString & filter = QString(),
QString * selectedFilter = 0,
Options optiOns= 0)


  • parent: 父窗口

  • caption: 标题

  • dir:打开时的目录

  • filter: 过滤器。过滤器就是用于过滤特定的后缀名。如果我们使用“Image Files(.jpg * .png)”,则只能显示后缀名是 jpg 或者 png 的文件。如果需要多个过滤器,使用“;;”分割,比如“JPEG Files( .jpg);;PNG Files(* .png)”;

  • selectedFilter: 默认选择的过滤器

  • options:对话框的一些参数设定,比如只显示文件夹等等,它的取值是 enum QFileDialog::Option,每个选项可以使用 | 运算组合起来

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle(tr("Main Window"));
openAction = new QAction(tr("&Open..."), this);
openAction->setShortcut(QKeySequence::Open);
openAction->setStatusTip(tr("Open an existing file"));
connect(openAction, &QAction::triggered, this, &MainWindow::open);
QMenu *file = this->menuBar() -> addMenu(tr("&File"));
file->addAction(openAction);
saveAction = new QAction(tr("&Save"));
saveAction->setShortcut(QKeySequence::Save);
saveAction->setStatusTip(tr("Save this file"));
connect(saveAction, &QAction::triggered, this, &MainWindow::save);
file->addAction(saveAction);
QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);
textEdit = new QTextEdit();
setCentralWidget(textEdit);
statusBar();
}
void MainWindow::open() {
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::save() {
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("Can not open file:\n%1").arg(path));
return;
}
QTextStream out(&file);
out <toPlainText();
file.close();
} else {
QMessageBox::warning(this, tr("Path"), tr("You did not select any file.\n"));
}
}

image-20210207114917640



推荐阅读
author-avatar
铁匠他夫人_738
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有