您的位置:首页 > 编程语言 > C语言/C++

QML 与C++函数互相调用

2017-04-05 19:30 369 查看
QML函数可在C++中调用,反之亦然.

所有的QML函数都被暴漏在了元数据系统中,并可通过QMetaObject::invokeMethod()调用.C++应用程序调用QML函数:

// MyItem.qml
import QtQuick 1.0

Item {
function myQmlFunction(msg) {
console.log("Got message:", msg)
return "some return value"
}
}

// main.cpp
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, msg));

qDebug() << "QML function returned:" << returnedValue.toString();


注意QMetaObject::invokeMethod()中Q_RETURN_ARG() 和Q_ARG()的参数必须指定为QVariant类型,这是QML函数和返回值的通用数据类型.

在QML中调用C++函数,函数必须是Qt的槽或标记了Q_INVOKABLE宏的函数,才能在QML中访问.下面范例中,QML代码调用了(使用QDeclarativeContext::setContextProperty()设置到QML中的)myObject对象的方法:

// MyItem.qml
import QtQuick 1.0

Item {
width: 100; height: 100

MouseArea {
anchors.fill: parent
onClicked: {
myObject.cppMethod("Hello from QML")
myObject.cppSlot(12345)
}
}
}

//main.cpp
class MyClass : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE void cppMethod(const QString &msg) {
qDebug() << "Called the C++ method with" << msg;
}

public slots:
void cppSlot(int number) {
qDebug() << "Called the C++ slot with" << number;
}
};

int main(int argc, char *argv[]) {
QApplication app(argc, argv);

QDeclarativeView view;
MyClass myClass;
view.rootContext()->setContextProperty("myObject", &myClass);

view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();

return app.exec();
}


QML支持调用C++的重载函数.如果C++中有多个同名不同参的函数,将根据参数数量和类型调用正确的函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: