首页 > 其他分享 >Qt之菜单栏中文件的写入、打开、保存

Qt之菜单栏中文件的写入、打开、保存

时间:2022-11-01 23:22:58浏览次数:38  
标签:return Qt QMessageBox QAction 写入 fileName file 菜单栏 MainWindow

在常见的记事本中,通常都有打开文件,写入文件、保存文件等功能,今天就用Qt来写一下记事本的打开、写入、保存等功能

一、创建菜单栏

   QMenu *fileMenu = menuBar()->addMenu("File");
    QToolBar *fileToolBar = addToolBar("File");

    QAction *newAct = new QAction(QIcon(":/images/new.png"), "New", this);
    //添加快捷键
    newAct->setShortcuts(QKeySequence::New);
    //状态栏提示
    newAct->setStatusTip(tr("Create a new file"));
    connect(newAct, &QAction::triggered, this, &MainWindow::newFile);

    //添加菜单栏
    fileMenu->addAction(newAct);
    //添加工具栏
    fileToolBar->addAction(newAct);

    QAction *openAct = new QAction(QIcon(":/images/open.png"), "Open...", this);
    openAct->setShortcuts(QKeySequence::Open);
    openAct->setStatusTip("Open an existing file");
    connect(openAct, &QAction::triggered, this, &MainWindow::open);
    fileMenu->addAction(openAct);
    fileToolBar->addAction(openAct);

    QAction *saveAct = new QAction(QIcon(":/images/save.png"), "Save", this);
    saveAct->setShortcuts(QKeySequence::Save);
    saveAct->setStatusTip("Save the document to disk");
    connect(saveAct, &QAction::triggered, this, &MainWindow::save);
    fileMenu->addAction(saveAct);
    fileToolBar->addAction(saveAct);

    QAction *saveAsAct = fileMenu->addAction("Save As...", this, &MainWindow::saveAs, QKeySequence::SaveAs);
    saveAsAct->setStatusTip("Save the document under a new name");

    //添加分割线
    fileMenu->addSeparator();

    QAction *exitAct = fileMenu->addAction("Exit", this, &QWidget::close);
    exitAct->setShortcuts(QKeySequence::Quit);
    exitAct->setStatusTip("Exit the application");

    //创建状态栏
    statusBar()->showMessage(tr("Ready"));

 

 

 

 

 三、文件的写入并保存

bool MainWindow::save()
{
    if (curFile.isEmpty()) {
        return saveAs();
    } else {
        return saveFile(curFile);
    }
}
bool MainWindow::saveAs()
{
    QFileDialog dialog(this);
    dialog.setWindowModality(Qt::WindowModal);
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    if (dialog.exec() != QDialog::Accepted)
        return false;
    return saveFile(dialog.selectedFiles().first());
}
bool MainWindow::saveFile(const QString &fileName)
{
    QString errorMessage;

    QGuiApplication::setOverrideCursor(Qt::WaitCursor);
    QSaveFile file(fileName);
    if (file.open(QFile::WriteOnly | QFile::Text)) {
        QTextStream out(&file);
        out << textEdit->toPlainText();
        if (!file.commit()) {
            errorMessage = tr("Cannot write file %1:\n%2.")
                           .arg(QDir::toNativeSeparators(fileName), file.errorString());
        }
    } else {
        errorMessage = tr("Cannot open file %1 for writing:\n%2.")
                       .arg(QDir::toNativeSeparators(fileName), file.errorString());
    }
    QGuiApplication::restoreOverrideCursor();

    if (!errorMessage.isEmpty()) {
        QMessageBox::warning(this, "error", errorMessage);
        return false;
    }

    setCurrentFile(fileName);
    statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

三、打开新文件

bool MainWindow::maybeSave()
{
    //监测文本框中的内容是否修改,如何修改则保存
    if (!textEdit->document()->isModified())
        return true;
    
    const QMessageBox::StandardButton ret
        = QMessageBox::warning(this, "error",
                               "The document has been modified.\n"
                                  "Do you want to save your changes?",
                               QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
    switch (ret) {
    case QMessageBox::Save:
        return save();
    case QMessageBox::Cancel:
        return false;
    default:
        break;
    }
    return true;
}
void MainWindow::open()
{
    if (maybeSave()) {
        QString fileName = QFileDialog::getOpenFileName(this);
        if (!fileName.isEmpty())
            loadFile(fileName);
    }
}
void MainWindow::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Application"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(QDir::toNativeSeparators(fileName), file.errorString()));
        return;
    }

    QTextStream in(&file);
    QGuiApplication::setOverrideCursor(Qt::WaitCursor);
    textEdit->setPlainText(in.readAll());
    QGuiApplication::restoreOverrideCursor();

    setCurrentFile(fileName);
    statusBar()->showMessage(tr("File loaded"), 2000);
}

 

标签:return,Qt,QMessageBox,QAction,写入,fileName,file,菜单栏,MainWindow
From: https://www.cnblogs.com/QingYiShouJiuRen/p/16849551.html

相关文章

  • Qt执行耗时操作导致界面卡顿的三种解决办法
    1.问题描述Qt界面程序开发中,会遇到执行耗时操作时,导致界面卡顿。原因是界面主线程是单线程,如果在UI主线程中执行耗时操作,例如点击按钮,响应函数去数据库查询数据,数据量比较......
  • 在Winform程序中设置管理员权限及为用户组添加写入权限
    在Winform程序中设置管理员权限及为用户组添加写入权限2017-12-04 1514简介:在我们一些Winform程序中,往往需要具有一些特殊的权限才能操作系统文件,我们可以设置运行程......
  • Qt编写本地摄像头综合应用示例(qcamera/ffmpeg/v4l2等)
    一、功能特点同时支持qcamera、ffmpeg、v4l2三种内核解析本地摄像头。提供函数findCamera自动搜索环境中的所有本地摄像头设备,搜索结果信号发出。支持自动搜索和指......
  • 【QT】创建动态链接库及使用
    创建动态链接库创建一个项目选择library的C++库,下一步。选择共享库,输入动态库的名字,选择创建路径,下一步选择编译环境,下一步选择QTCore模块,该模块提供核心的非图......
  • Qt+VLC简单的使用显示视频Demo
    先看看效果: vlc播放视频,要比QMediaPlayer实用的多,并且同时运行20个视频时不会出现卡顿。 这个Demo功能实现非常简单,简单的说一下vlc流程:1、创建并初始化一个libvlc实例LI......
  • Qt检测U盘插入拔出Demo
    要做这个,要先知道Qt的QAbstractNativeEventFilter类,虚函数nativeEventFilter。这个类的主要作用是捕获全局windows消息。先看一下效果:基本注意以下两点:1、新建的类要继承QAb......
  • Qt5.6作浏览器Demo可查看地图
    这里用到了ui提升部件的小方法,记得设置控件为Microsoft webbrowser,先看看效果:用到ui里面的QAxWidget控件,用以下这个类来提升这个控件。#include<ActiveQt/QAxWidget>#inc......
  • Qt用Poppler库解析PDF成图片的简单示例
    解析PDF这里用的是Poppler库,与之相关的库还有MuPDF库,参考了这个链接:​​https://people.freedesktop.org/~aacid/docs/qt5/​​相关链接:​​qt显示pdf——poppler-qt问题​......
  • Qt对Json的生成与解析Demo
    QJsonObject类用于封装JSON对象。JSON对象是键值对,其中键是唯一的字符串,其值由QJsonValue代表。一个QJsonObject可以从QVariantMap转换/被转换。QJsonArray类用于封装JSON数......
  • Qt创建和删除文件小Demo(顺便讲了补全功能)
    背景:笔者需要创建和删除多个pdd和多个pff文件(这些是自己创建的类型),一个个手动创建和删除很麻烦,就做了一款小软件解决此问题。先看一下效果:代码如下:①、头文件:#ifndefMAINWI......