是从C 中更新QML梯度值的最佳方法

Whats the best way to update the gradient value in QML from C++?

本文关键字:最佳 方法 更新 QML 是从      更新时间:2023-10-16

在我的qml文件中,我的梯度定义如下:

ColorizedRoundedButton
{
   gradient: Gradient   
           {
             GradientStop { position: 0.0; color: "#3f5c43" }            
             GradientStop { position: 0.33; color: "#113d14" }            
             GradientStop { position: 0.66; color: "#023105" }            
             GradientStop { position: 1.0; color: "#056508" }    
           }
}

因此,在这里,我希望通过样式表应用此梯度值,即从C 设置此值。

我有类似的style.h文件:

#include <QLinearGradient>
Q_DECLARE_METATYPE(QLinearGradient)
class Style: public QObject
{
  Q_PROPERTY(QLinearGradient PositiveGradient READ getPositiveGradient WRITE setPositiveGradient)
  QLinearGradient _positiveGradient;
  QLinearGradient getPositiveGradient();
  void setPositiveGradient(QLinearGradient p_grad);
}

使用这种方法将qlineargradient类型用作q_property,然后将QML文件更改为:

gradient: style.PositiveGradient 

这种方法不起作用,我会遇到运行时错误,因为无法将qlineargradient分配给qquickgradient*。

任何人都知道该解决方案或任何更好的解决方案,以传递C 和QML之间的梯度值?

声明类:

class Style: public QObject
{
    Q_OBJECT
    
 public:
    explicit Style(QObject *parent = nullptr)
    {}
public slots:
    QStringList stops()
    {
        QLinearGradient gradeint(0, 0, 1, 100);
        gradeint.setColorAt(0, "red");
        gradeint.setColorAt(1, "black");
    
        QStringList colors;
    
        for (const auto &g : gradeint.stops())
        {
            colors.append(g.second.name());
        }
    
        return colors;
    }
};

您写了此类后,用QML注册并写入:

Rectangle {
id: root
    gradient: Gradient {
        id:gradient
    }
    Component
    {
        id:stopComponent
        GradientStop {}
    }
    Component.onCompleted:
    {
        var stops = Style.stops()
        var stopsList = [];
        var length = stops.length;
        for (let i = 0; i < length; i++) {
            var s1 = stopComponent.createObject(root, {"position": i / length , "color": stops[i]});
            stopsList.push(s1)
        }
        gradient.stops = stopsList
    }
}