今天又重新看了下QML 和c++ 交互,记个笔记。。
原文:
C++ 类型定义可参考之前的文章:
QML < 5 > QML 访问C++ 类 (函数Q_INVOKABLE、枚举Q_ENUMS 、成员变量Q_PROPERTY、自定义结构体(QVariantMap )、List数据QVariantList 、信号signal 、槽slot)
QQmlComponent、QQuickView( QWindow派生类 ) 可以加载QML 文件
import QtQuick 2.0
Item {
width: 100; height: 100
}
使用QQmlComponent 需要调用QQmlComponent::create() 创建一个新的 qml文件实例
// Using QQmlComponent
QQmlEngine engine;
QQmlComponent component(&engine,
QUrl::fromLocalFile("MyItem.qml"));
QObject *object = component.create();
...
delete object;
QQuickView 自定创建qml文件实例,可通过 QQuickView::rootObject() 访问
// Using QQuickView
QQuickView view;
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
QObject *object = view.rootObject();
获得qml对象后 可通过 QObject::setProperty() 或者 QQmlProperty::write() 修改属性,
object->setProperty("width", 500);
QQmlProperty(object, "width").write(500);
区别在于 QQmlProperty::write()后解除属性绑定,
例 QML中 width :wgt_width
QObject::setProperty() 后修改wgt_width ,width 值会更新,而 QQmlProperty::write() 后修改wgt_width ,width 值不变
访问QML中的方法 QMetaObject::invokeMethod()
Q_RETURN_ARG() 和 Q_ARG() 为QVariant 类型
QML
// MyItem.qml
import QtQuick 2.0
Item {
function myQmlFunction(msg) {
console.log("Got message:", msg)
return "some return value"
}
}
C++
// main.cpp
QQmlEngine engine;
QQmlComponent 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();
delete object;
MyClass myClass;
QObject::connect(item, SIGNAL(qmlSignal(QString)),
&myClass, SLOT(cppSlot(QString)));
QObject::findChildren() 可以找到所有匹配的objectName 对象
import QtQuick 2.0
Item {
width: 100; height: 100
Rectangle {
anchors.fill: parent
objectName: "rect"
}
}
QObject *rect = object->findChild("rect");
if (rect)
rect->setProperty("color", "red");