QObjectComputedProperty Class
template <typename Class, typename T, auto Offset, auto Getter> class QObjectComputedPropertyQObjectComputedProperty 类是一个模板类,可帮助将旧属性移植到可绑定属性系统。更多
Header: | #include <QObjectComputedProperty> |
CMake: | find_package(Qt6 REQUIRED COMPONENTS Core) target_link_libraries(mytarget PRIVATE Qt6::Core) |
qmake: | QT += core |
自 | Qt 6.0 |
继承于 | QUntypedPropertyData |
宏
(since 6.0) | Q_OBJECT_COMPUTED_PROPERTY(containingClass, type, name, callback) |
详细描述
QObjectComputedProperty 是一个只读属性,每次读取时都会重新计算。它不存储计算值。它是实现Qt 可绑定属性的 Qt 内部类之一。通常不会直接使用 QObjectComputedProperty,而是通过使用Q_OBJECT_COMPUTED_PROPERTY 宏来创建它的实例。
请参阅以下示例。
class Client{}; class MyClassPrivate : public QObjectPrivate { public: QList<Client> clients; bool hasClientsActualCalculation() const { return clients.size() > 0; } Q_OBJECT_COMPUTED_PROPERTY(MyClassPrivate, bool, hasClientsData, &MyClassPrivate::hasClientsActualCalculation) }; class MyClass : public QObject { Q_OBJECT Q_PROPERTY(bool hasClients READ hasClients STORED false BINDABLE bindableHasClients) public: QBindable<bool> bindableHasClients() { return QBindable<bool>(&d_func()->hasClientsData); } bool hasClients() const { return d_func()->hasClientsData.value(); } void addClient(const Client &c) { Q_D(MyClass); d->clients.push_back(c); // notify that the value could have changed d->hasClientsData.notify(); } private: Q_DECLARE_PRIVATE(MyClass) };
可绑定属性获取器和设置器中的获取器规则同样适用于 QObjectComputedProperty。特别是,获取器应该是琐碎的,只返回 QObjectComputedProperty 对象的值。给 QObjectComputedProperty 的回调器通常应是一个私有方法,仅由 QObjectComputedProperty 调用。
由于 QObjectComputedProperty 是只读的,因此不需要也不允许使用设置器。
为了正确参与依赖关系处理,QObjectComputedProperty 必须知道它的值,即给它的回调结果,何时可能发生变化。每当回调中使用的可绑定属性发生变化时,这种情况就会自动发生。如果回调的结果可能因非绑定属性值的变化而改变,开发人员有责任在 QObjectComputedProperty 对象上调用notify
。这将告知从属属性可能发生的变化。
请注意,调用notify
可能会触发从属属性中的更改处理程序,而从属属性又可能会使用 QObjectComputedProperty 所属的对象。因此,当处于过渡或无效状态时,不得调用notify
。
QObjectComputedProperty 不适用于依赖于任何可能在未通知的情况下发生变化的输入(如文件内容)的计算。
另请参阅 Q_OBJECT_COMPUTED_PROPERTY,QProperty,QObjectBindableProperty,Qt 的属性系统和Qt 可绑定属性。
宏文档
[since 6.0]
Q_OBJECT_COMPUTED_PROPERTY(containingClass, type, name, callback)
在containingClass 中声明一个QObjectComputedProperty ,类型为type ,名称为name 。参数callback 指定了属性评估时调用的 GETTER 函数。
此宏在 Qt 6.0 中引入。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.