作者:铁匠他夫人_738 | 来源:互联网 | 2023-09-05 19:57
文件对话框目录文件对话框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"));
}
}