无法使用 QStandardPath 打开文件

Can't open file using QStandardPaths

本文关键字:文件 QStandardPath      更新时间:2023-10-16

我正在尝试创建一个程序,当我按下按钮时打开一个文件。我在头文件中创建了一个QStandardPath。然后,我将/myfile.txt附加到它的末尾,并尝试打开它。我刚开始使用Qt,希望得到一些建议。

dialog.h:

#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QStandardPaths>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
    Q_OBJECT
public:
    QString Location = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
private slots:
    void on_btn_Read_clicked();
private:
    Ui::Dialog *ui;
};
#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QStringList>
#include <QFile>
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}
Dialog::~Dialog()
{
    delete ui;
}
void Dialog::on_btn_Read_clicked()
{
    QFile myFile(Location.append("/myfile.txt"));
    if(!myFile.exists())
    {
        qDebug() << "File does not exist. attempting to create. . .";
        if (myFile.open(QIODevice::ReadWrite | QIODevice::Text)){
            qDebug() << "created :]";
        }
        else
        {
            qDebug() << "not created :[";
        }
    }
    myFile.close();
}

应该检查给定的目录是否存在。如果没有,则需要创建完整路径,例如:

QDir().mkpath( /**/ );

只能在此之后创建文件

QFile file( filename );
if ( file.opne( /**/ ) )
{
    // ...
}

(但所有这些都是在你确定你得到许可之后。)