16——Chapter 2: Connecting to C++ Methods and Signals
最后更新于:2022-04-01 07:21:41
本系列所有文章可以在这里查看[http://blog.csdn.net/cloud_castle/article/category/2123873](http://blog.csdn.net/cloud_castle/article/category/2123873)
接上文[Qt5官方demo解析集15——Chapter 1: Creating a New Type](http://blog.csdn.net/cloud_castle/article/details/36873203)
在上篇博文我们了解到如何在C++代码中将一个C++类注册为一个QML类型,并供QML文件使用。接下来这个Demo中进一步向这个PieChart中添加信号和方法供QML使用。
在项目上没有什么改变,我们直接来看代码PieChart.h:
~~~
#ifndef PIECHART_H
#define PIECHART_H
#include <QtQuick/QQuickPaintedItem>
#include <QColor>
//![0]
class PieChart : public QQuickPaintedItem
{
//![0]
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(QColor color READ color WRITE setColor)
//![1]
public:
//![1]
PieChart(QQuickItem *parent = 0);
QString name() const;
void setName(const QString &name);
QColor color() const;
void setColor(const QColor &color);
void paint(QPainter *painter);
//![2]
Q_INVOKABLE void clearChart(); // 使用Q_INVOKABLE宏将该函数注册到Qt的元系统中,这样QML才能对它进行处理
signals:
void chartCleared(); // 接着像通常一样定义了一个信号
//![2]
private:
QString m_name;
QColor m_color;
//![3]
};
//![3]
~~~
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;
}
void PieChart::setColor(const QColor &color)
{
m_color = color;
}
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);
}
//![0]
void PieChart::clearChart() // 在该函数中我们将饼图设置为透明,并更新显示,然后发射“已清理”信号
{
setColor(QColor(Qt::transparent));
update();
emit chartCleared();
}
//![0]
~~~
main函数没有变化,我们直接看看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
color: "red"
onChartCleared: console.log("The chart has been cleared") // 我们可以像其他QML类型一样定义它的信号处理函数
}
MouseArea { // 当鼠标左键点击时调用自定义函数
anchors.fill: parent
onClicked: aPieChart.clearChart()
}
Text {
anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 }
text: "Click anywhere to clear the chart"
}
}
~~~
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-18_569cbd0764e16.jpg)![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-18_569cbd077264c.jpg)