Reading and writing files in QML (Qt)

后端 未结 4 1861

I am trying to implement Reading and writing files in QML and came across the linked article from Nokia but have not been able to successfully use the seemingly obvious code

4条回答
  •  没有蜡笔的小新
    2020-12-19 04:35

    A complete example of FileIO can be found on this page: https://qmlbook.github.io/ch17-extensions/extensions.html#fileio-implementation

    class FileIO : public QObject {
        ...
        Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
        Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
        ...
    public:
        Q_INVOKABLE void read();
        Q_INVOKABLE void write();
        ...
    }
    

    We will leave out the properties, as they are simple setters and getters.

    The read method opens a file in reading mode and reads the data using a text stream.

    void FileIO::read()
    {
        if(m_source.isEmpty()) {
            return;
        }
        QFile file(m_source.toLocalFile());
        if(!file.exists()) {
            qWarning() << "Does not exits: " << m_source.toLocalFile();
            return;
        }
        if(file.open(QIODevice::ReadOnly)) {
            QTextStream stream(&file);
            m_text = stream.readAll();
            emit textChanged(m_text);
        }
    }
    

    When the text is changed it is necessary to inform others about the change using emit textChanged(m_text). Otherwise, property binding will not work.

    The write method does the same but opens the file in write mode and uses the stream to write the contents.

    void FileIO::write()
    {
        if(m_source.isEmpty()) {
            return;
        }
        QFile file(m_source.toLocalFile());
        if(file.open(QIODevice::WriteOnly)) {
            QTextStream stream(&file);
            stream << m_text;
        }
    }
    

    And source code can be found here: https://github.com/qmlbook/qmlbook/tree/master/docs/ch17-extensions/src/fileio

提交回复
热议问题