QML文件讀寫控件(預覽版)

旨在解決QML不能讀寫文件的問題。目前爲預覽版本(文末源碼),供大家一起參考學習。

  File組件通過source的屬性來設置需要讀寫的文件,還可以通過訪問/設置text的內容來讀取/寫入文件

demo.gif

使用

  • 註冊File組件到Qml中:
qmlRegisterType<File>("MyModel", 1, 0, "File");
  • 導入File組件:
import MyModel 1.0
  • 使用:
/* 創建實例 */
File {
    id: file
    source: "D:/Document/hello.txt"
}

TextArea {
    anchors.fill: parent
    font.pixelSize: 30
    onTextChanged: file.text = text
    Component.onCompleted: text = file.text
}

源碼

  • main.cpp
#include "File.h"

int main(int argc, char *argv[])
{
    ...
    qmlRegisterType<File>("MyModel", 1, 0, "File");
    ...
}
  • File.h
#ifndef QT_HUB_FILE_H
#define QT_HUB_FILE_H

#include <QObject>

class File : public QObject
{
    Q_OBJECT
public:
    File();

    Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged)
    Q_PROPERTY(QString text   READ text   WRITE setText   NOTIFY textChanged)

    QString source() const;
    void setSource(const QString &source);

    QString text() const;
    void setText(const QString &text);

signals:
    void sourceChanged();
    void textChanged();

private slots:
    void readFile();

private:
    QString m_source;
    QString m_text;
};

#endif // FILE_H
  • File.cpp
#include "File.h"

#include <QFile>
#include <QDebug>

File::File()
{
    connect(this, SIGNAL(sourceChanged()), this, SLOT(readFile()));
}

void File::setSource(const QString &source)
{
    m_source = source;
    emit sourceChanged();
}

QString File::source() const
{
    return m_source;
}

void File::setText(const QString &text)
{
    QFile file(m_source);
    if (!file.open(QIODevice::WriteOnly)) {
        m_text = "";
        qDebug() << "Error:" << m_source << "open failed!";
    }
    else {
        qint64 byte = file.write(text.toUtf8());
        if (byte != text.toUtf8().size()) {
            m_text = text.toUtf8().left(byte);
            qDebug() << "Error:" << m_source << "open failed!";
        }
        else {
            m_text = text;
        }

        file.close();
    }

    emit textChanged();
}

void File::readFile()
{
    QFile file(m_source);
    if (!file.open(QIODevice::ReadOnly)) {
        m_text = "";
        qDebug() << "Error:" << m_source << "open failed!";
    }

    m_text = file.readAll();
    emit textChanged();
}

QString File::text() const
{
    return m_text;
}
  • main.qml
...
import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 2.0
import MyModel 1.0

Window {
    visible: true
    width: 480
    height: 320
    title: qsTr("File組件 by Qt君")

    File {
        id: file
        source: "D:/Document/hello.txt"
    }

    TextArea {
        anchors.fill: parent
        font.pixelSize: 30
        onTextChanged: file.text = text
        Component.onCompleted: text = file.text
    }
}

第一時間獲取最新推送,請關注微信公衆號Qt君

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章