Qt6 QML Book/扩展QML/FileIO实现

FileIO Implementation

FileIO实现

Remember the FileIO API we want to create should look like this.

记住我们要创建的FileIO API应该是这样的。

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.

我们将省略这些属性,因为它们是简单的setter和getter。

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

read方法以读取模式打开文件,并使用文本流读取数据。

void FileIO::read()
{
    if(m_source.isEmpty()) {
        return;
    }
    QFile file(m_source.toLocalFile());
    if(!file.exists()) {
        qWarning() << "Does not exist: " << 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.

当文本发生更改时,有必要使用emit textChanged(m_text)通知其他人更改。否则,属性绑定将无法工作。

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

write方法也会这样做,但会以写入模式打开文件,并使用流写入文本属性text的内容。

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

To make the type visible to QML, we add the QML_ELEMENT macro just after the Q_PROPERTY lines. This tells Qt that the type should be made available to QML. If you want to provide a different name than the C++ class, you can use the QML_NAMED_ELEMENT macro.

为了使类型对QML可见,我们在Q_PROPERTY行之后添加QML_ELEMENT宏。这会告诉Qt应该将该类型提供给QML。如果你想提供一个不同于C++类的名字,你可以使用QML_NAMED_ELEMENT宏。

TODO TODO TODO

Do not forget to call make install at the end. Otherwise, your plugin files will not be copied over to the qml folder and the qml engine will not be able to locate the module.

不要忘记在最后调用make install。否则,插件文件将不会复制到qml文件夹,qml引擎将无法找到该模块。

TODO TODO TODO

TIP

As the reading and writing are blocking function calls you should only use this FileIO for small texts, otherwise, you will block the UI thread of Qt. Be warned!

由于读写操作会阻止函数调用,所以只能将此FileIO用于小文本,否则会阻止Qt的UI线程。小心!

示例源码下载 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值