如何将附加属性传播给Qml中的子级?

问题描述

我想制作诸如Material.accent之类的东西,在其中我可以更改父级和子级以获取父级属性定义。

这是我目前的方式,但是我在文档中找不到有关此信息。 我知道有可能,“材质样式”也使用此方法以及诸如font属性之类的其他内容

class MyThemeAttached : public QObject {
    Q_OBJECT

    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
    QML_ANONYMOUS

public:
    explicit MyThemeAttached(QObject* parent = nullptr)
        : QObject(parent),m_color("#FF0000"){}

    QColor color() const;
    void setColor(const QColor color);

signals:
    void backgroundChanged(QColor background);

private:
    QColor m_color;
};


class MyTheme : public QObject
{
    Q_OBJECT
    QML_ATTACHED(MyThemeAttached)
    QML_ELEMENT
public:
    explicit MyTheme(QObject *parent = nullptr);

    static MyThemeAttached *qmlAttachedProperties(QObject *object) {
        return new MyThemeAttached(object);
    }
};


applicationwindow {
    id: root
    visible: true
    width: 800
    height: 600
    title: qsTr("Window")
    
    MyCustomProperty.color: "orange"

    Rectangle {
        color: MyCustomProperty.color        
    }
}

解决方法

为什么不看Material的代码?我向您介绍Woboq.org。

Here,您会看到Material主题实际上是主动将主题推向子级:

void QQuickMaterialStyle::propagateTheme()
{
    const auto styles = attachedChildren();
    for (QQuickAttachedObject *child : styles) {
        QQuickMaterialStyle *material = qobject_cast<QQuickMaterialStyle *>(child);
        if (material)
            material->inheritTheme(m_theme);
    }
}