如何在QML中调用C++的方法并接收C++的信号

    技术2022-05-20  35

    在QML中调用c++方法并接收信号 继续上一篇的内容使用C++创建新的QML类型,接下来我们在PieChart 这个类中添加一个函数"clearChart()" 和一个信号"chartCleared",这样在app.qml中就可以像下面一样调用这个函数,并接收这个信号了: import Charts 1.0 import QtQuick 1.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")      }        MouseArea {          anchors.fill: parent          onClicked: aPieChart.clearChart()      }        Text {          anchors { bottom: parent.bottom; horizontalCenter: parent.horizontalCenter; bottomMargin: 20 }          text: "Click anywhere to clear the chart"      }  } File:SimpleChart2.png‎ 为c++类添加被调用的方法和信号 下面我们就来看一下在C++的类中我们具体应该怎么做: class PieChart : public QDeclarativeItem  {      ...  public:      ...      Q_INVOKABLE void clearChart();    signals:      void chartCleared();      ...  }; 使用Q_INVOKABLE 使得Qt Meta-Object 系统可以访问到clearChart() 方法,于是QML也可以访问到这个方法了。请注意,由于槽函数(slots)也可以被QML调用,因此clearChart() 也可以被声明为一个Qt slot 而不使用Q_INVOKABLE。这两种方式都是有效的。 clearChart() 方法将绘制扇形图的画笔颜色设置成Qt::transparent(透明),并重绘扇形图,最后发出chartCleared()信号: void PieChart::clearChart()  {      setColor(QColor(Qt::transparent));      update();        emit chartCleared();  } 运行程序 现在我们可以启动这个应用程序并点击其窗口区域,于是窗口上的扇形图就消失了,并且应用程序有如下输出: The chart has been cleared 大家可以在 Qt 的 examples/tutorials/extending/chapter2-methods目录中找到这个程序的完整代码。


    最新回复(0)