Qt : 实现打开 +保存 +另存功能实现

qt中设置文件保存的几种方式:txt

QFileDialog for "Save As" with choices

QT的使用——QT文件操作和事件实现文件保存(**)

Qt弹出对话框按指定路径保存图片

QT创建一个excel文件(通过save as 方法) : QAxObject *excel = new QAxObject(this);https://blog.csdn.net/venice0708/article/details/92087023 



 

Qt将文件保存到指定目录下(另存为的功能

Qt将文件保存到指定目录下(另存为的功能)_qt保存路径_丁老师的技术随笔的博客-CSDN博客

Qt 官方手册:getSaveFileName() (**)

============================

QFileDialog for "Save As" with choices

QFileDialog for "Save As" with choices | Qt Forum

Qt将文件保存到指定目录下(另存为的功能

Qt将文件保存到指定目录下(另存为的功能)_qt保存路径_丁老师的技术随笔的博客-CSDN博客

下面是另存为功能对话框选择保存路径即可。(简介版的)

QString fileName(tr("ok.txt")) ;  
 QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                  "/home",
                                               QFileDialog::ShowDirsOnly
                                                  | QFileDialog::DontResolveSymlinks);

    QDir d;
    d.mkpath(dir);//可以不用,因为路径已经有了,就不用mk了
    QFile file(dir+"/"+fileName);
    file.open(QFile::WriteOnly);

QT创建一个excel文件(通过save as 方法)  https://blog.csdn.net/venice0708/article/details/92087023

QString filepath = QFileDialog::getSaveFileName(this, QString::fromLocal8Bit("导出表格"), ".", tr("Microsoft Office(*.xlsx)"));//获取保存路径
    if (!filepath.isEmpty()) {
        QAxObject *excel = new QAxObject(this);
        excel->setControl("Excel.Application");//连接Excel控件
        excel->dynamicCall("SetVisible (bool Visible)", "false");//不显示窗体
        excel->setProperty("DisplayAlerts", false);//不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改,是否保存”的提示
 
        QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
        workbooks->dynamicCall("Add");//新建一个工作簿
        QAxObject *workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
        QAxObject *worksheets = workbook->querySubObject("Sheets");//获取工作表集合
        QAxObject *worksheet = worksheets->querySubObject("Item(int)", 1);//获取工作表集合的工作表1,即sheet1
        workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(filepath));//保存至filepath,注意一定要用QDir::toNativeSeparators将路径中的"/"转换为"\",不然一定保存不了。
        workbook->dynamicCall("Close()");//关闭工作簿
        excel->dynamicCall("Quit()");//关闭excel
        delete excel;
        excel = NULL;
    }
    return true;

qt中设置文件保存的几种方式:txt

归纳总结4种qt常用的文件保存的方式:

1、需要用到的头文件:

#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QTime>
#include <QTextStream>
#include <QDebug>

2、按钮的实现,如图所示

实现其中的一个:选择创建file

源码如下:

    //创建file,可以选择文件夹保存
    void MainWindow::on_Choose_file_clicked()
    {
        //创建一个file文件
        QFileDialog fileDialog;
        QString fileName = fileDialog.getSaveFileName(this,tr("Open File"),"/data",tr("Text File(*.txt)"));
        if(fileName == "")
        {
            return;
        }

        
        QFile file(fileName);//可以自己选择路径来保存文件名
        if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QMessageBox::warning(this,tr("错误"),tr("打开文件失败"));
            return;
        }
        else
        {
            QTextStream textStream(&file);
            QString str = ui->textEdit->toPlainText();//从textEdit里面回去内容,然后再直接拿来用
            textStream<<str;
            QMessageBox::warning(this,tr("提示"),tr("保存文件成功"));
            file.close();
        }
    }

可以实现创建一个data.txt的文件,并且文件还可以实现选择路径

具体源码请参考:https://download.csdn.net/download/littlehero_121/11594279


————————————————
版权声明:本文为CSDN博主「Littlehero_121」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Littlehero_121/article/details/100018392

Qt弹出对话框按指定路径保存图片

Qt弹出对话框按指定路径保存图片_qimage保存tif_草帽小子Coder的博客-CSDN博客

void balser_c::SavePictureTriggered(QPixmap img)
{
    
    QImage img2 = img.toImage();
    
    QString filename = QFileDialog::getSaveFileName(this,
                                                    tr("Save Image"),
                                                    "",
                                                    tr("*.bmp;; *.png;; *.jpg;; *.tif;; *.GIF")); //选择路径
    if (filename.isEmpty())
    {
        return;
    }
    else
    {
        if (!(img2.save(filename))) //保存图像
        {
            
            QMessageBox::information(this,
                                     tr("Failed to save the image"),
                                     tr("Failed to save the image!"));
            return;
        }
        ui.statusBar->showMessage("图片保存成功");
    }
    
}

————————————————
版权声明:本文为CSDN博主「草帽小子Coder」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39485901/article/details/88056369

Qt入门-打开和保存文件对话框

Qt入门-打开和保存文件对话框_qt打开文件对话框和保存文件对话框_xgbing的博客-CSDN博客

使用QFileDialog可以方便地调用当前系统的文件对话框:

(1)文件打开对话框

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

示例:

        QString fileName;
        fileName = QFileDialog::getOpenFileName(this,
            tr("Open Config"), "", tr("SCD Files (*.scd);; CID Files (*.cid)"));
     
        if (!fileName.isNull())
        {
                //fileName即是选择的文件名
        }
            else
                //点是的取消


 


(2)文件保存对话框

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


示例:

        QString fileName;
        fileName = QFileDialog::getSaveFileName(this,
            tr("Open Config"), "", tr("Config Files (*.ifg)"));
     
        if (!fileName.isNull())
        {
                         //fileName是文件名
              }
             else
                          //点的是取消


设置文件过滤的示例

"Image Files (*.png *.jpg *.bmp)"  //多个文件使用空格分隔

"Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"   //多个过滤使用两个分号分隔

 
————————————————
版权声明:本文为CSDN博主「xgbing」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xgbing/article/details/7828149

QT的使用——QT文件操作和事件实现文件保存(**)

4、QT的使用——QT文件操作和事件实现文件保存_qt保存文件_weixin_45981798的博客-CSDN博客

目录

一、文件操作

1、ui界面

2、mainwindow.h

3、新建文件的功能

(1)构造函数中:(信号与槽的连接)

(2)新建文件槽函数

4、打开某个文件

(1)添加头文件

(2)获取文件并且将信息显示在文本框中

5、将一个文件的数据读出来,并且将数据另存为另一个文件

 二、事件

1、重写虚函数

2、键盘按下(ctr+s保存)

3、鼠标按下

一、文件操作
1、ui界面

(1)选择textEdit,然后选择垂直布局,保证文本框会随着框的大小变化而变化

(2)输入栏目名时,要写上”文件(&F)",就会显示”文件(F)“,才可通过快捷键打开菜单

(3)预览的快捷键:Alt+Shift+R
2、mainwindow.h

    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
        void keyPressEvent(QKeyEvent *k);
        void mousePressEvent(QMouseEvent *m);
     
    private slots:
        void newActionSlot();
        void openActionSlot();
        void saveActionSlot();

3、新建文件的功能
(1)构造函数中:(信号与槽的连接)

 connect(ui->newAction, &QAction::triggered, this, &MainWindow::newActionSlot);

(2)新建文件槽函数

    void MainWindow::newActionSlot()
    {
        ui->textEdit->clear();
        this->setWindowTitle("新建文本文档.txt");
    }

4、打开某个文件

(1)添加头文件

#include <QFileDialog>

(2)获取文件并且将信息显示在文本框中

    void MainWindow::openActionSlot()
    {
        QString fileName = QFileDialog::getOpenFileName(this, "选择一个文件",
                     QCoreApplication::applicationFilePath(), "*.cpp");
        if (fileName.isEmpty())
        {
            QMessageBox::warning(this, "警告", "请选择一个文件");
        }
        else
        {
            //qDebug() << fileName;
            QFile file(fileName);    //创建文件对象
            file.open(QIODevice::ReadOnly);
            QByteArray ba = file.readAll();
            ui->textEdit->setText(QString(ba));
            file.close();
        }
    }

    当前路径下: QCoreApplication::applicationFilePath()

    若要指定路径:”/home“

5、将一个文件的数据读出来,并且将数据另存为另一个文件

    void MainWindow::saveActionSlot()
    {
        QString fileName = QFileDialog::getSaveFileName(this, "选择一个文件",
                    QCoreApplication::applicationFilePath());
        if (fileName.isEmpty())
        {
            QMessageBox::warning(this, "警告", "请选择一个文件");
        }
        else
        {
            QFile file(fileName);
            file.open(QIODevice::WriteOnly);//打开文件
            //ui->textEdit->toPlainText();
            QByteArray ba;
            ba.append(ui->textEdit->toPlainText());//将数组读出来
            file.write(ba);
            file.close();
        }
    }

 二、事件
1、重写虚函数

    #include <QMessageBox>
    #include <QDebug>
    #include <QKeyEvent>
    #include <QMouseEvent>
     
     
    void keyPressEvent(QKeyEvent *k);
    void mousePressEvent(QMouseEvent *m);

2、键盘按下(ctr+s保存)

    void MainWindow::keyPressEvent(QKeyEvent *k)
    {
        if (k->modifiers() == Qt::ControlModifier && k->key() == Qt::Key_S)
        {
            saveActionSlot();
        }
    }

3、鼠标按下

    void MainWindow::mousePressEvent(QMouseEvent *m)
    {
        QPoint pt = m->pos();//获取鼠标的位置
        qDebug() << pt;//打印出鼠标的位置
     
        if (m->button() == Qt::LeftButton)
        {
            qDebug() << "左键被按下";
        }
        else if (m->button() == Qt::RightButton)
        {
            qDebug() << "右键被按下";
        }
    }


————————————————
版权声明:本文为CSDN博主「weixin_45981798」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45981798/article/details/129476687

Qt 官方手册:getSaveFileName() (**)

[static] QString QFileDialog::getSaveFileName(QWidget *parent = nullptr, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = nullptr, QFileDialog::Options options = Options())
This is a convenience static function that will return a file name selected by the user. The file does not have to exist.
It creates a modal file dialog with the given parent widget. If parent is not nullptr, the dialog will be shown centered over the parent widget.

  QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                             "/home/jana/untitled.png",
                             tr("Images (*.png *.xpm *.jpg)"));

The file dialog's working directory will be set to dir. If dir includes a file name, the file will be selected. Only files that match the filter are shown. The filter selected is set to selectedFilter. The parameters dir, selectedFilter, and filter may be empty strings. Multiple filters are separated with ';;'. For instance:

  "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)"

The options argument holds various options about how to run the dialog, see the QFileDialog::Option enum for more information on the flags you can pass.
The default filter can be chosen by setting selectedFilter to the desired value.
The dialog's caption is set to caption. If caption is not specified, a default caption will be used.
On Windows, and macOS, this static function will use the native file dialog and not a QFileDialog.
On Windows the dialog will spin a blocking modal event loop that will not dispatch any QTimers, and if parent is not nullptr then it will position the dialog just below the parent's title bar. On macOS, with its native file dialog, the filter argument is ignored.
On Unix/X11, the normal behavior of the file dialog is to resolve and follow symlinks. For example, if /usr/tmp is a symlink to /var/tmp, the file dialog will change to /var/tmp after entering /usr/tmp. If options includes DontResolveSymlinks the file dialog will treat symlinks as regular directories.
Warning: Do not delete parent during the execution of the dialog. If you want to do this, you should create the dialog yourself using one of the QFileDialog constructors.
See also getOpenFileName(), getOpenFileNames(), and getExistingDirectory().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值