引言
继续上一章 在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](http://www.developer.nokia.com/Community/Wiki/images/e/e3/QMLListProperty.png?20110330085050)
代码实现
为实现这一点,我们把 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
相关链接