上下文
自定义的类型PieChart
//piechart.h
#ifndef PIECHART_H
#define PIECHART_H
//![0]
#include <QtQuick/QQuickPaintedItem>
#include <QColor>
class PieChart : public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(QColor color READ color WRITE setColor)
public:
PieChart(QQuickItem *parent = 0);
QString name() const;
void setName(const QString &name);
QColor color() const;
void setColor(const QColor &color);
void paint(QPainter *painter);
private:
QString m_name;
QColor m_color;
};
//![0]
#endif
//piechart.cpp
#include "piechart.h"
#include <QPainter>
//![0]
PieChart::PieChart(QQuickItem *parent)
: QQuickPaintedItem(parent)
{
}
//![0]
QString PieChart::name() const
{
return m_name;
}
void PieChart::setName(const QString &name)
{
m_name = name;
}
QColor PieChart::color() const
{
return m_color;
}
void PieChart::setColor(const QColor &color)
{
m_color = color;
}
//![1]
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);
}
//![1]
通过qmlRegisterType注册
qmlRegisterType<PieChart>("Charts", 1, 0, "PieChart");
qml中使用
//app.qml
import Charts 1.0
import QtQuick 2.0
Item {
width: 300; height: 200
PieChart {
id: aPieChart
anchors.centerIn: parent
width: 100; height: 100
name: qsTr("A simple pie chart")
// @disable-check M16
color: "red"
}
Text {
y: 140
text: aPieChart.name
anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 48 }
anchors.horizontalCenterOffset: -72
}
Text {
id: text1
x: 150
y: 165
width: 105
height: 15
text: aPieChart.name
font.pixelSize: 12
}
}
代码中Text对象中引用了PieChart对象中的name属性,由于name属性被引用,运行时报错
QQmlExpression: Expression qrc:///app.qml:79:15 depends on non-NOTIFYable properties:
PieChart::name
QQmlExpression: Expression qrc:///app.qml:68:15 depends on non-NOTIFYable properties:
PieChart::name
原因
属性name被引用,当name值被修改时,需要通知所有引用该字段用于更新,但未定义NOTIFY属性
解决办法
添加name属性的NOTIFY属性和信号定义
//piechart.h Modified
#ifndef PIECHART_H
#define PIECHART_H
//![0]
#include <QtQuick/QQuickPaintedItem>
#include <QColor>
class PieChart : public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
Q_PROPERTY(QColor color READ color WRITE setColor)
public:
PieChart(QQuickItem *parent = 0);
QString name() const;
void setName(const QString &name);
QColor color() const;
void setColor(const QColor &color);
void paint(QPainter *painter);
signals:
void nameChanged();
private:
QString m_name;
QColor m_color;
};
//![0]
#endif