无法使用 QStandardPaths 打开文件
Can't open file using QStandardPaths
我正在尝试创建一个在我按下按钮时打开文件的程序。我在头文件中创建了一个 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( /**/ ) )
{
// ...
}
(但所有这些都是在你确定你有权限之后才做的。)
我正在尝试创建一个在我按下按钮时打开文件的程序。我在头文件中创建了一个 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( /**/ ) )
{
// ...
}
(但所有这些都是在你确定你有权限之后才做的。)