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

 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:显示操作过程。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值