17——Chapter 3: Adding Property Bindings
最后更新于:2022-04-01 07:21:43
本系列所有文章可以在这里查看[http://blog.csdn.net/cloud_castle/article/category/2123873](http://blog.csdn.net/cloud_castle/article/category/2123873)
接上文[Qt5官方demo解析集16——Chapter 2: Connecting to C++ Methods and Signals](http://blog.csdn.net/cloud_castle/article/details/36882625)
在C++中我们通常将用户的交互与处理函数用信号槽绑定起来,比如窗口尺寸的变化,颜色的变化等,但在QML中,我们更多的使用属性绑定来完成这些功能。我们可以将这个属性值绑定到另一个对象或者本身的属性值上,这样当后者改变时,前者也能够跟着发生改变,而不需要我们在一个专门的onXXX()函数中进行这样的处理。
同样的,这个工程进一步在上一个例子上进行扩展,虽然代码只有简单的改动,我们还是将其全部贴出来piechart.h:
~~~
#ifndef PIECHART_H
#define PIECHART_H
#include <QColor>
#include <QtQuick/QQuickPaintedItem>
//![0]
class PieChart : public QQuickPaintedItem
{
//![0]
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
//![1]
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) // 我们为Q_PROPERTY添加了NOTIFY特性
public: // 告诉编译器该属性值发生变化时"colorChanged"信号将被发出
//![1] // 这样我们不再需要特别为该信号写onColorChanged()处理函数
PieChart(QQuickItem *parent = 0);
QString name() const;
void setName(const QString &name);
QColor color() const;
void setColor(const QColor &color);
void paint(QPainter *painter);
Q_INVOKABLE void clearChart();
//![2]
signals:
void colorChanged();
//![2]
private:
QString m_name;
QColor m_color;
//![3]
};
//![3]
#endif
~~~
PieChart.cpp:
~~~
#include "piechart.h"
#include <QPainter>
PieChart::PieChart(QQuickItem *parent)
: QQuickPaintedItem(parent)
{
}
QString PieChart::name() const
{
return m_name;
}
void PieChart::setName(const QString &name)
{
m_name = name;
}
QColor PieChart::color() const
{
return m_color;
}
//![0]
void PieChart::setColor(const QColor &color) // 动态赋予颜色
{
if (color != m_color) {
m_color = color;
update(); // repaint with the new color
emit colorChanged(); // 发出信号
}
}
//![0]
void PieChart::paint(QPainter *painter)
{
QPen pen(m_color, 2);
painter->setPen(pen);
painter->setRenderHints(QPainter::Antialiasing, true);
painter->drawPie(boundingRect().adjusted(1, 1, -1, -1), 90 * 16, 290 * 16);
}
void PieChart::clearChart()
{
setColor(QColor(Qt::transparent));
update();
}
~~~
app.qml:
~~~
import Charts 1.0
import QtQuick 2.0
Item {
width: 300; height: 200
Row {
anchors.centerIn: parent
spacing: 20
PieChart {
id: chartA
width: 100; height: 100
color: "red" // 初始化赋为红色
}
PieChart {
id: chartB
width: 100; height: 100
color: chartA.color // 属性绑定
}
}
MouseArea {
anchors.fill: parent
onClicked: { chartA.color = "blue" } // 点击后将A赋为蓝色,B由于属性绑定也变成蓝色
}
Text {
anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 }
text: "Click anywhere to change the chart color"
}
}
//![0]
~~~
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-18_569cbd0784312.jpg)![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-18_569cbd0792b5e.jpg)