简体   繁体   English

在Qt5 / Qml中无法写入文件

[英]Writing to file doesn’t work in Qt5/Qml

for my QML project I need a simple IODevice to work with files so I took this one from Nokia Dev But I tweaked it a little, for purposes of my work. 对于我的QML项目,我需要一个简单的IODevice来处理文件,因此我从Nokia Dev那里获得了一个文件,但出于工作目的,我对其进行了一些调整。 Reading from file works like a charm(this proves, that there is no “wrong path to file” problem”), but writing to file is broken, and I can't find a reason why. 从文件读取就像一个符咒(这证明,没有“文件路径错误”的问题”),但写入文件已损坏,我找不到原因。

Here is the code: 这是代码:

fileio.h fileio.h

#ifndef FILEIO_H
#define FILEIO_H

#include <QObject>

class FileIO : public QObject
{
    Q_OBJECT

public:
    explicit FileIO(QObject *parent = 0);

    Q_INVOKABLE QString read(const QString& Url);
    Q_INVOKABLE bool write(const QString& Url, QString data);


public slots:

signals:
    void error(const QString& msg);

private:
    QString mSource;
};

#endif // FILEIO_H

fileio.cpp fileio.cpp

#include "fileio.h"
#include <QFile>
#include <QTextStream>

FileIO::FileIO(QObject *parent) :
    QObject(parent)
{

}

QString FileIO::read(const QString& Url)
{
    mSource = Url;
    if (mSource.isEmpty()){
        emit error("source is empty");
        return QString();
    }

    QFile file(mSource);
    QString fileContent;
    if ( file.open(QIODevice::ReadOnly) ) {
        QString line;
        QTextStream t( &file );
        t.setCodec("UTF-8");
        do {
            line = t.readLine();
            fileContent += line;
         } while (!line.isNull());

        file.close();
    } else {
        emit error("Unable to open the file");
        return QString();
    }



    return fileContent;
}

bool FileIO::write(const QString& Url, QString data)
{
    mSource = Url;
    if (mSource.isEmpty()){
        emit error("source is empty");
        return false;}

        QFile file(mSource);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            emit error("Error");
            return false;}

        QTextStream out(&file);
        out << data;
        //emit error("data:" + data); //This one was used to debug, Yet no errors were emmited when Write is called


        file.close();

        return true;
}

I needed my app to load settings from external file (I cant use QSettings, as I wish to give user access these settings by external script or through text editor when app is not launched). 我需要我的应用程序从外部文件加载设置(我不能使用QSettings,因为我希望允许用户在未启动应用程序时通过外部脚本或文本编辑器访问这些设置)。 So for every setting I have a file with a single Utf-8 string, which is loaded into qml (smth like 因此,对于每个设置,我都有一个带有单个Utf-8字符串的文件,该文件已加载到qml中(

property string interfacecolor1 : myFile.read("://settings/color1");

), and it works. ),并且有效。 But I also want to change settings in qml Example would be: 但我也想在qml中更改设置,例如:

TextField{
                id:fieldsurname
                Layout.fillWidth: true
                text: myFile.read("://settings/surname"); //Shows user current setting, works perfectly
                onTextChanged: {console.log(fieldsurname.text); //I just check if textfield behaves as supposed, returns what I expect from it.
myFile.write("://settings/surname", fieldsurname.text); //Write text from textfield (it will be for an embeded platform, so I probably need to change setting every new char)
surname = myFile.read("://settings/surname"); //I write new setting to property from new text from file
console.log(myFile.read("://settings/surname")) //Returns an unchanged string
}
            }

Also forgot to mention, that manualy editing files also works, settings are changed accordingly, app behaves as it should. 还忘了提及,手动编辑文件也可以使用,相应地更改了设置,应用行为正常。

So the question is: What is wrong? 所以问题是:怎么了?

Ps: this is a duplicate of this question on qt-project but the question got burried, and I need an answer ASAP. 附言:这是qt-project上该问题的重复部分,但这个问题很隐秘,我需要尽快回答。 Thanks in advance. 提前致谢。

Qrc files are read-only. Qrc文件是只读的。 You cannot write to them. 您无法写信给他们。 You'll have to put the file into the real filesystem and read/write it from/to there. 您必须将文件放入真实的文件系统中,然后从那里读/写文件。

You can use QSettings to save the settings of your application : 您可以使用QSettings保存应用程序的设置:

QSettings settings("organizationName","applicationName");
settings.setValue("settings/surname",fieldsurname.text);

Or read them : 或阅读它们:

surname = settings.value("settings/surname","").toString();

But in case it is necessary to use files(You may want to import settings from other devices using files) You should note that the files in Qt resources are readonly. 但是,如果有必要使用文件(您可能希望使用文件从其他设备导入设置),则应注意Qt资源中的文件是只读的。 So you should first copy your file to some location if you want to change it: 因此,如果要更改文件,应首先将文件复制到某个位置:

QFile dfile("://settings/surname");
if (dfile.exists())
{
     dfile.copy("./surname");
     QFile::setPermissions("./surname",QFile::WriteOwner | QFile::ReadOwner);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM