您的位置:首页 > 编程语言 > Qt开发

QT5入门之17 - 文件选择对话框

2015-10-27 14:27 405 查看
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
NULL,
tr("txtFile (*.* *.txt)"));
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return;
}


fileName 返回选择的文件,下面的使用QFile打开文件(只读方式)。

文件保存对话框类似。

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."));
}
}


内置对话框:

QColorDialog:选择颜色;

QFileDialog:选择文件或者目录;

QFontDialog:选择字体;

QInputDialog:允许用户输入一个值,并将其值返回;

QMessageBox:模态对话框,用于显示信息、询问问题等;

QPageSetupDialog:为打印机提供纸张相关的选项;

QPrintDialog:打印机配置;

QPrintPreviewDialog:打印预览;

QProgressDialog:显示操作过程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: