利用qmlRegisterType接口注册一个文件操作类到Qml中,这样Qml就可以实现读写文件。
1 FileObject.h
代码语言:javascript复制#ifndef FILE_OBJECT_H
#define FILE_OBJECT_H
#include <QObject>
class FileObject : public QObject
{
Q_OBJECT
Q_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
代码语言:javascript复制#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中
代码语言:javascript复制#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.0
Rectangle {
width: 640
height: 320
Text {
id: myText
anchors.centerIn: parent
}
FileObject{
id: fileObject
source: "test.txt"
}
MouseArea {
anchors.fill: parent
onClicked: {
fileObject.write("Hello world!!!");
myText.text = fileObject.read();
}
}
}