利用qmlRegisterType接口注册一个文件操作类到Qml中,这样Qml就可以实现读写文件。
1 FileObject.h
#ifndef FILE_OBJECT_H
#define FILE_OBJECT_H#include <QObject>class FileObject : public QObject
{Q_OBJECTQ_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged)
public:explicit FileObject(QObject *parent = 0);Q_INVOKABLE QString read();Q_INVOKABLE bool write(const QString& data);void setSource(const QString& source) { m_source = source; };QString source() { return m_source; }signals:void sourceChanged(const QString& source);private:QString m_source;
};#endif // FILE_OBJECT_H
2 FileObject.cpp
#include "FileObject.h"#include <QFile>
#include <QTextStream>FileObject::FileObject(QObject *parent) :QObject(parent)
{}QString FileObject::read()
{QString content;QFile file(m_source);if ( file.open(QIODevice::ReadOnly) ) {content = file.readAll();file.close();} return content;
}bool FileObject::write(const QString& data)
{QFile file(m_source);if ( file.open(QFile::WriteOnly | QFile::Truncate) ) {QTextStream out(&file);out<<data;file.close();return true;}else {return false;}
}
3 注册FileObject到Qml中
#include "FileObject.h"Q_DECL_EXPORT int main(int argc, char *argv[])
{...qmlRegisterType<FileObject>("FileObject", 1, 0, "FileObject");...
}
4 在Qml中使用FileObject实例
- 读文件内容
fileObject.read();
- 写文件
fileObject.write("Hello world!!!")
;
import QtQuick 1.1
import FileObject 1.0Rectangle {width: 640height: 320Text {id: myTextanchors.centerIn: parent}FileObject{id: fileObjectsource: "test.txt"}MouseArea {anchors.fill: parentonClicked: {fileObject.write("Hello world!!!");myText.text = fileObject.read();}}
}