展示如何通过C++类去扩展QML
创建一个QML新类型“PieChart”,我们希望该新类型包括两个属性:名字(name)和颜色(color),我们希望通过导入Chart 1.0 命名空间来使用它,使用方法如下所示:
import Charts 1.0
PieChart {
width: 100; height: 100
name: "A simple pie chart"
color: "red"
}
C++类要求
1、继承自QObject
2、使用宏 Q_PROPERTY声明属性
PieChart类
piechart.h
#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;
};
为了重载QQuickPaintedItem::paint()使用QPainter API画想要的内容,PieChart类继承自QQuickPaintedItem。如果该类仅仅包含数据类型,不需要显示,仅仅需要继承QObject即可。如果需要创建一个可视item,但是不包括使用QPainter API画的操作,我们仅仅需要继承自QQuickItem即可。
piechart.cpp
PieChart::PieChart(QQuickItem *parent)
: QQuickPaintedItem(parent)
{
}
...
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);
}
app.xml
import Charts 1.0
import QtQuick 2.0
Item {
width: 300; height: 200
PieChart {
id: aPieChart
anchors.centerIn: parent
width: 100; height: 100
name: "A simple pie chart"
color: "red"
}
Text {
anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 }
text: aPieChart.name
}
}
main.cpp调用方法
#include "piechart.h"
#include <QtQuick/QQuickView>
#include <QGuiApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<PieChart>("Charts", 1, 0, "PieChart");
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:///app.qml"));
view.show();
return app.exec();
}
运行效果