• 600阅读
  • 2回复

[提问]QML如何在外部修改Rect的图片 [复制链接]

上一主题 下一主题
离线qq2632671
 

只看楼主 倒序阅读 楼主  发表于: 2023-08-10
RT
首先是一个Rect,我需要把这个作为一个组件在别的文件里使用
  1. //ChangeImg.qml
  2. Rectangle {
  3.     width : 100;
  4.     height : 100
  5.     Image{
  6.         id:imgx
  7.         source : "A1.png"
  8.         anchors.fill : parent
  9.     }
  10. }
然后是使用这个组件
  1. //mian.qml
  2. Column{
  3.     ChangeImg{
  4.         id:a1
  5.         width : 100
  6.         height : 100
  7.     }
  8.     ChangeImg{
  9.         id:a2
  10.         width : 100
  11.         height : 100
  12.     }
  13.     Component.onCompleted : {
  14.         //a2.Image.source = "A2.png";   #语句1
  15.         //ChangeImg.imgx.source = "A2.png";   #语句2
  16.         //a1.imgx.source = "know.png";   #语句3
  17.     }
  18. }
现在因为某些需求,需要在Column中修改Rect中的图片
语句1 :无效
语句2 :QML提示"file:///D:/QML/TestImg/main.qml:16: TypeError: Value is undefined and could not be converted to an object"
语句3 : 结果同语句2

所以,如何在这个Column中修改Rect的图片?
离线20091001753

只看该作者 1楼 发表于: 2023-08-10
//ChangeImg.qml
Rectangle {
    width : 100;
    height : 100
    property alias imasou: imgx.source
    Image{
        id:imgx
        source : "A.png"
        anchors.fill : parent
    }
}

//mian.qml
Component.onCompleted : {
    a1.imasou = "B.png"
}
(づ ̄ 3 ̄)づ
离线qq2632671

只看该作者 2楼 发表于: 2023-08-11
回 20091001753 的帖子
20091001753:
//ChangeImg.qml
Rectangle {
    width : 100;
    height : 100
    property alias imasou: imgx.source
.......

非常感谢,顺利在问个问题,我用了alias后确实可以在Rect外部通过a1.imasou修改图片,但我其实是通过JS函数来修改图片的,在Rect外部有个JS函数
  1. function changeImg(){
  2.     a1.imasou = "A1.png";
  3. }
类似上面这种,但我运行是提示
file:///E:/QML/ChangeImg.js:23: TypeError: Cannot assign to read-only property "imasou"
这种情况怎么解决?
快速回复
限100 字节
 
上一个 下一个