0

Qt を使用してファイルとの間でデータを保存およびロードする最も簡単な方法は何ですか?

これを行う方法の例を教えてください。

4

1 に答える 1

2

slotQMLシグナルハンドラーで呼び出される書き込み用のパブリックを作成できます。

次に、Q_INVOKABLE返されたデータで読み取るためのメソッド、または void 戻り値で読み取るためのスロットのいずれかを作成できます。後者の場合、目的のプロパティにマップされたデータ プロパティを使用することができます。

全体として、適切なソリューションは、まだ提供されていないより多くのコンテキストに依存します。

クラスにはマクロを含める必要があり、残念ながら、シグナルスロットメカニズムと、QML エンジンが現時点で s を中心に構築されているという事実のために、クラスQ_OBJECTを継承する必要があります。うまくいけば、それは将来変わるかもしれません。QObjectQObject

myclass.h

class MyClass : public QObject
{
    Q_OBJECT
    // Leaving this behind comment since I would not start off with this.
    // Still, it might be interesting for your use case.
    // Q_PROPERTY(QByteArray data READ data WRITE setData NOTIFY dataChanged)
    public:
        MyClass() {} // Dummy for now because it is not the point
        ~MyClass() {} // Dummy for now because it is not the point

   Q_INVOKABLE QByteArray read();
   QByteArray data() const ;

   public slots:
       // void read(); // This would read into the internal variable  for instance
       void write(QByteArray data) const;

   // private:
       // QByteArray m_data;
};

myclass.cpp

/* 
void MyClass::read()
{
    QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    // You could also use the readAll() method in here.
    // Although be careful for huge files due to memory constraints
    while (!in.atEnd()) {
        QString line = in.readLine();
        m_data.append(line);
    }
}
*/

QByteArray MyClass::read()
{
    QByteArray data;
    QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    // You could use readAll() here, too.
    while (!in.atEnd()) {
        QString line = in.readLine();
        data.append(line);
    }

    file.close();
    return data;
}

void MyClass::write(QByteArray data)
{
    QFile file("out.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out.write(data);
    file.close();
}

それが完了したら、次の方法でこの機能を QML に公開できます。

main.cpp

...
MyClass *myClass = new MyClass();
viewContext->setContextProperty("MyClass", myClass);
...

次に、次のように QML からこれらの関数を呼び出すことができます。

main.qml

...
Page {
    Button {
        text: "Read"
        onClicked: readLabel.text = myClass.read()
    }

    Label {
        id: readLabel
    }

    Button {
        text: "Write"
        onClicked: myClass.write()
    }
}
...

免責事項:私はこのコードを生のテキストのように書いていたので、コンパイルされなかったり、赤ちゃんを食べたりする可能性がありますが、背後にあるアイデアを示す必要があります. 最終的に、読み取り操作と書き込み操作用の 2 つのボタンと、読み取られたファイルの内容を表示する 1 つのラベルが表示されます。

于 2013-12-31T17:20:53.240 に答える