QObjectComputedProperty Class
template <typename Class, typename T, auto Offset, auto Getter> class QObjectComputedPropertyQObjectComputedProperty 类是一个模板类,用于帮助将旧属性迁移到可绑定属性系统中。更多内容...
| 头文件: | #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 是一个模板类,其中模板参数Class 指定所属的QObject 派生类,T 指定计算属性值的类型,Offset 指定该属性在类中的位置,Getter 指定用于计算属性值的成员函数。
QObjectComputedProperty 是一个只读属性,每次读取时都会重新计算。它不存储计算出的值。它是实现Qt 可绑定属性的 Qt 内部类之一。通常不会直接使用 QObjectComputedProperty,而是通过使用Q_OBJECT_COMPUTED_PROPERTY 宏来创建其实例。
请参见以下示例。
class Client{};
class MyClassPrivate : public QObject
{
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 是只读的,因此不要求也不允许有 setter。
为了正确参与依赖处理,QObjectComputedProperty 必须知道其值(即传递给它的回调的结果)何时可能发生变化。 每当回调中使用的可绑定属性发生变化时,此过程会自动触发。如果回调结果可能因某个非可绑定属性的值发生变化而改变,则开发者有责任在 QObjectComputedProperty 对象上调用notify 。这将通知依赖属性可能发生的变化。
请注意,调用notify 可能会触发依赖属性中的变更处理程序,而这些处理程序可能会进一步使用 QObjectComputedProperty 所属的对象。因此,在过渡状态或无效状态下,切勿调用notify 。
QObjectComputedProperty 不适用于依赖于可能在未预先通知的情况下发生变化的输入(例如文件内容)的计算。
另请参阅 Q_OBJECT_COMPUTED_PROPERTY 、QProperty 、QObjectBindableProperty 、Qt 的属性系统以及Qt 可绑定属性。
成员函数文档
[default] QObjectComputedProperty::QObjectComputedProperty()
默认构造一个QObjectComputedProperty 的实例。
宏文档
[since 6.0] Q_OBJECT_COMPUTED_PROPERTY(containingClass, type, name, callback)
在containingClass 中声明一个类型为type 、名称为name 的QObjectComputedProperty 。参数callback 指定了在评估该属性时要调用的GETTER函数。
该宏在 Qt 6.0 中引入。
另请参阅 QObjectBindableProperty 、Qt 的属性系统以及Qt 可绑定属性。
© 2026 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.