报错截图
报错代码
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.2
Window {
visible: true
width: 640
height: 480
title: qsTr("定位器嵌套")
Rectangle{
width:640;
height:480;
color:"#EEEEEE";
id:rootItem;
Text{
id:centerText;
text:"hello";
anchors.centerIn: parent;
font.pixelSize: 24;
font.bold: true;
}
function setTextColor(clr){
centerText.color=clr;
}
Row{
anchors.left:parent.left;
anchors.leftMargin: 4;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 4;
spacing:4;
Column{
spacing:4;
ColorPicker{
color:Qt.rgba(Math.random(),Math.random(),Math.random(),1.0);
onColorPicked:{
setTextColor(clr);
}
}
ColorPicker{
color:Qt.rgba(Math.random(),Math.random(),Math.random(),1.0);
onColorPicked:{
setTextColor(clr);
}
}
}
}
Column{
spacing:4;
ColorPicker{
color:Qt.rgba(Math.random(),Math.random(),Math.random(),1.0);
onColorPicked:{
setTextColor(clr);
}
}
ColorPicker{
color:Qt.rgba(Math.random(),Math.random(),Math.random(),1.0);
onColorPicked:{
setTextColor(clr);
}
}
}
Column{
spacing:4;
ColorPicker{
color:Qt.rgba(Math.random(),Math.random(),Math.random(),1.0);
onColorPicked:{
setTextColor(clr);
}
}
ColorPicker{
color:Qt.rgba(Math.random(),Math.random(),Math.random(),1.0);
onColorPicked:{
setTextColor(clr);
}
}
}
}
}
报错原因
函数是在Rectangle下定义的,却被下一级调用,作用域不对。
解决方法
使用Rectangle的id来调用setTextColor函数。
rootItem.setTextColor(clr);