Qml读文件内容

利用qmlRegisterType接口注册一个文件操作类到Qml中,这样Qml就可以实现读写文件。

1 FileObject.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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中

1
2
3
4
5
6
7
8
#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!!!");
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    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();
    }
    }
    }