在QML C++ extension 中使用 ListProperty 类型

在QML C++ extension 中使用 ListProperty 类型

引言

继续上一章 在QML中使用自定义属性类型 的内容。到目前为止,PieChart 只能拥有一个PieSlice。但是在理想情况下一张图表可能有多个部分,每部分有不同的颜色和属性。为实现这一点我们需要有一个可以接收多个 PieSlice 元素的 slices 属性,就像下面这样:

import Charts 1.0
import QtQuick 1.0
 
 Item {
     width: 300; height: 200
 
     PieChart {
         anchors.centerIn: parent
         width: 100; height: 100
 
         slices: [
             PieSlice {
                 anchors.fill: parent
                 color: "red"
                 fromAngle: 0; angleSpan: 110
             },
             PieSlice {
                 anchors.fill: parent
                 color: "black"
                 fromAngle: 110; angleSpan: 50
             },
             PieSlice {
                 anchors.fill: parent
                 color: "blue"
                 fromAngle: 160; angleSpan: 100
             }
         ]
     }
 }

QMLListProperty.png

代码实现

为实现这一点,我们把 PieChart 中的 pieSlice 属性替换为类型为 QDeclarativeListProperty 的 slices 属性。 QDeclarativeListProperty 类使得在 QML 扩展中创建 list 属性成为可能。我们将 pieSlice() 函数替换为slices() 函数,slices() 函数返回一个 slices 的列表。并且增加一个私有函数 append_slice() 。我们还使用了一个 QList m_slices 来存储 slices 的列表:

class PieChart : public QDeclarativeItem
 {
     Q_OBJECT
     Q_PROPERTY(QDeclarativeListProperty<PieSlice> slices READ slices)
     ...
 public:
     ...
     QDeclarativeListProperty<PieSlice> slices();
 
 private:
     static void append_slice(QDeclarativeListProperty<PieSlice> *list, PieSlice *slice);
 
     QString m_name;
     QList<PieSlice *> m_slices;
 };



虽然slices 属性没有一个与之相关的WRITE 方法,但是它仍然是可以被修改的,这是由QDeclarativeListProperty 的工作方式决定的。在PieChart的具体实现中,我们让PieChart::slices() 返回一个 QDeclarativeListProperty 的值,并且指出每当从QML中发出向列表中添加元素的请求时候就调用PieChart::append_slice() 函数:

QDeclarativeListProperty<PieSlice> PieChart::slices()
 {
     return QDeclarativeListProperty<PieSlice>(this, 0, &PieChart::append_slice);
 }
 
 void PieChart::append_slice(QDeclarativeListProperty<PieSlice> *list, PieSlice *slice)
 {
     PieChart *chart = qobject_cast<PieChart *>(list->object);
     if (chart) {
         slice->setParentItem(chart);
         chart->m_slices.append(slice);
     }
 }

PieChart::append_slice() 函数和之前一样设置了slice的parent,并向m_slices 链表添加新元素。大家可以看到,append_slice()被调用的时候接收了两个参数:list 属性,和要被添加的item。


我们对PieSlice 这个类也进行了修改,添加了fromAngle 和 angleSpan 属性,并且根据这些值来绘制Slice。这些修改是很简单的,这里就不再赘述。

下载例程

Media:QMLCppListProperty.zip

相关链接

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值