qml样式化时qml类型转换错误

时间:2019-02-20 01:54:57

标签: qt qml

首先,我发现了两个帖子,并希望尝试如下的可换肤的想法:

我几乎复制了他们的代码,但是失败了,并且发生了错误:

while code running , it reports error showing "Unable to assign AbstractStyle_QMLTYPE_37 to AbstractStyle_QMLTYPE_0".

这是我的代码:

// AbstractStyle.qml
import QtQuick 2.0
QtObject {
 property int textSize;
 property color textColor;
}

// StyleA.qml
import QtQuick 2.0
AbstractStyle {
 textSize : 20
 textColor : "red"
}

// StyleB.qml
import QtQuick 2.0
AbstractStyle {
 textSize : 50
 textColor : "green"
}

//componentCreation.js
var component;
var sprite;
function createStyleObject(item, stylePath)
{
 component = Qt.createComponent(stylePath);
 if( component.status == Component.Ready ){
  sprite = component.createObject(item);
  console.log("[!!!OK!!!]componentCreation.js:" + stylePath + " component ready");
}
else
 console.log("componentCreation.js:" + stylePath + " component not ready");
if (sprite === null)
 console.log("componentCreation.js: error creating " + stylePath + " object");
else
 return sprite;
}

//main.cpp
int main(int argc, char *argv[]) {
 QGuiApplication app(argc, argv);

 QQuickView *view = new QQuickView;
 view->setResizeMode(QQuickView::SizeRootObjectToView);
 view->setSource(QUrl(QStringLiteral("qrc:///main.qml")));
 view->show();

 return app.exec();
}

//main.qml
import "qrc:/styles/componentCreation.js" as Style
Item {
 id : base
 ...
 property AbstractStyle currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");

 Text {
  x: 100
  y: 0
  font.pixelSize: currentStyle.textSize
  color: currentStyle.textColor
  text: "Hello World"
 }
 ...
}

Plus:开发环境是Windows中的vs2015和Ubuntu中的qtcreator,都使用了Qt 5.10.1

1 个答案:

答案 0 :(得分:0)

@eyllanesc @TrebuchetMS谢谢你们

好吧,经过一些测试,可以得出结论:

这适用于Qt 5.12.0及更高版本

property AbstractStyle currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");

这两个版本在Qt 5.10.1及更高版本中起作用

property QtObject currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");
property var currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");