QMLベースのファイル読み書き


最近グループの友达と交流して、突然私がまだqmlの中でローカルのファイルの机能を使うことがないことを発见して、QMLのTextの要素を调べて、意外にもsourceのこの属性がローカルのテキストのファイルをロードするなどがなくて、実はjsももともとioを操作することができなくて、しかしQMLはC++を接続口として処理して、なぜかこのような属性を提供していないで、すぐこの机能を研究しました.
QMLがこのような属性と方法を提供しない以上、私たちはC++から自分で操作ファイルのクラスを書いて、ファイルを処理するしかありません.
主にQObjectを継承するクラスです.次はコードです.
      
#ifndef FILEIO_H
#define FILEIO_H

#include <QObject>
#include <QTextStream>
#include <QFile>
class FileIO : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(QString source
               READ source
               WRITE setSource
               NOTIFY sourceChanged)
    explicit FileIO(QObject *parent = 0);

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

    QString source() { return mSource; };

public slots:
    void setSource(const QString& source) { mSource = source; };

signals:
    void sourceChanged(const QString& source);
    void error(const QString& msg);

private:
    QString mSource;
};

#endif // FILEIO_H
#include "fileio.h"
#include <QFile>

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

}

QString FileIO::read()
{
    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 );
        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& data)
{
    if (mSource.isEmpty())
        return false;

    QFile file(mSource);
    if (!file.open(QFile::WriteOnly | QFile::Truncate))
        return false;

    QTextStream out(&file);
    out << data;

    file.close();

    return true;
}
FileIO操作クラス
その後main関数にこの操作クラスを登録できます
#include <QtQml>
#include "fileio.h"

int main(int argc, char *argv[])
{
.................    
    qmlRegisterType<FileIO, 1>("FileIO", 1, 0, "FileIO");
.............
}

QMLには次のものがあります.
import QtQuick 2.0
import FileIO 1.0

Rectangle {
    width: 300
    height: 700
    BorderImage {
        id: name
        source: "background.png"
        width: 300; height: 700
        border.left: 5; border.top: 5
        border.right: 5; border.bottom: 5
    }
    Text {
        id: myText
        text: qsTr("       ")
        anchors.centerIn: parent
        font.pixelSize: 20
        color: "white"
    }
    FileIO {
           id: myFile
           source: "fileno.txt"
           onError: console.log(msg)
       }
       Component.onCompleted: {
           console.log( "WRITE"+ myFile.write("TEST TEST file is OK"));
           myText.text =  myFile.read();
       }
}

実はとても简単であなたがQMLを理解するだけでできて、简単ですが、しかしやはり再び记录して、后者が迅速に掌握することができるようにします
最後に私のgithub住所を添付します:寒山-居士-Github