一、引言
在《【Qml】QML和C++混合开发(01) - 将C++类公开给QML》一本中总结了如何向QML公开C++类的数据属性。那么对于C++类的方法同样也能公开给QML,本文将分享、总结如何向QML导出C++方法。
二、核心点记录
1、声明成员函数
对于QObject派生类型的任何方法都可以从QML代码中访问,例如:
(1)使用Q_INVOKABLE()宏标记的公共方法。
(2)公共Qt槽函数。
以上方法都可以在QML中方法到。
如下代码片段:
class MessageBoard : public QObject{
Q_OBJECT
public:
Q_INVOKABLE bool postMessage(const QString &msg) {
qDebug() << "Called the C++ method with" << msg;
return true;
}
public slots:
void refresh() {
qDebug() << "Called the C++ slot";
}
};
2、同样的,需要将类MessageBoard 注册到QML上下文环境中:
MessageBoard msgBoard; //实例MessageBoard
view.engine()->rootContext()->setContextProperty("cpp_msgBoard", &msgBoard); //将msgBoard注册到QML上下文环境中
3、在QML中使用C++类的方法
如下代码片段:
import QtQuick 2.0
Item {
width: 100; height: 100
MouseArea {
anchors.fill: parent
onClicked: {
var result = msgBoard.postMessage("Hello from QML")
console.log("Result of postMessage():", result)
msgBoard.refresh();
}
}