Label
{
objectName:'mylabel'
id:mylabel
text:'lalala'
font.pixelSize:24
color:'#008888'
function get_text(tempStr){return tenpStr + text
}
function get_pixsize(){return font.pixelSize
}
function get_color(){return color
}}
C++代码示例:
//从QML中读取属性,调用function
QObject* root = engine.rootObjects().first();//根对象auto mylabel = root->findChild<QObject*>("mylabel");//找到objectName为“mylabel”的对象qDebug()<<"font.pixelSize is "<<mylabel->property("font.pixelSize").toInt();//试图使用该方法访问font.pixelSize,实际返回0,因此该方法无法获取font.pixelSize,原因未知qDebug()<<"text is "<<mylabel->property("text").toInt();//可以访问text属性
QVariant ret;//用于保存qml中function的返回值QMetaObject::invokeMethod(mylabel,"get_color",Q_RETURN_ARG(QVariant, ret));//调用QML中无参数的get_color方法qDebug()<<"invokeMethod: get_color";qDebug()<<"value: "<<ret;qDebug()<<"type: "<<ret.type();//调用QML中有参数的get_text方法QMetaObject::invokeMethod(mylabel,"get_text",Q_RETURN_ARG(QVariant, ret),Q_ARG(QVariant,"text is "));//Q_RETURN_ARG指定返回值,Q_ARG指定输入的参数qDebug()<<"invokeMethod: get_text";qDebug()<<"value: "<<ret;qDebug()<<"type: "<<ret.type();