QML 对本地文件的读写
QML 里似乎没有提供直接访问本地文件的模块,但是我们能够自己扩展 QML,给它加上访问本地文件的能力。
Qt 官方文档对 QML 是这样介绍的:
It defines and implements the language and engine infrastructure, and provides an API to enable application developers to extend the QML language with custom types and integrate QML code with JavaScript and C++.
自定义模块
我们可以通过自定义 C++ 类,实现文件的读写并整合进 QML 中,使其作为一个文件读写的独立模块。
C++ 里这个类叫做 FileContent
头文件 FileContent.h:
#ifndef FILECONTENT_H
#define FILECONTENT_H
#include <QObject>
#include <QFile>
#include <QTextStream>
class FileContent : public QObject
{
Q_OBJECT
public:
Q_PROPERTY(QString content READ getContent)
Q_PROPERTY(QString filename READ getFileName WRITE setFileName)
Q_INVOKABLE QString getContent();
Q_INVOKABLE QString getFileName();
FileContent(QObject *parent = 0);
~FileContent();
private:
QFile *file;
QString co

本文介绍了如何在QML中扩展C++类实现本地文件读写,通过自定义模块FileContent集成到QML,并展示了使用JavaScript的XMLHttpRequest异步读取文件的方法。同时提到了QML的Settings模块用于配置文件读写,以及针对不同需求选择合适的方法。


被折叠的 条评论
为什么被折叠?



