• 2751阅读
  • 4回复

[提问]QtQuick在布局中动态添加组件的问题 [复制链接]

上一主题 下一主题
离线solo_wang
 

只看楼主 倒序阅读 楼主  发表于: 2019-01-30
回复本帖可获得10RMB金钱奖励!
每人最多可获奖1次,奖池剩余20RMB金钱 (中奖几率10%)
现在有个布局,比如说是Column{},在里面添加createComponent()动态创建的组件,这时候布局失效了,每个新创建的组件都是在(0,0)位置处。代码简化可以大概是下面的样子,有没有大佬给看看是不是我什么地方错了?
比如说有一个qml文件 test.qml

Item {
    id:root
    RadioButton{
        text:"测试一行"

    }

}
// main.qml
ApplicationWindow{
    id:root
    height:640
    width:480
    visible:true
    title:"测试"
    function add(){
        var component = Qt.createComponent("test.qml");
        if (component.status == Component.Ready) {
           var button = component.createObject(column);
        }else{
             console.log("Component.Error: ",component.errorString());
        }

    }

    Column{
        id:column
        spacing:10
    }
    Button{
       id:button
       anchors{bottom:parent.bottom;bottomMargin:10;}
       height:30;width:45;
       onClicked:
           add()

    }

    

}
离线maxlogo

只看该作者 1楼 发表于: 2019-01-30
回帖奖励+ 10
动态的Column需要使用Repeater,通过Repeater的model添加数据
个人博客:
简书:https://www.jianshu.com/u/14fa805306bd
CSDN:https://blog.csdn.net/qq10097355
思否:https://segmentfault.com/u/lowbees/articles
离线solo_wang

只看该作者 2楼 发表于: 2019-01-31
回 maxlogo 的帖子
maxlogo:动态的Column需要使用Repeater,通过Repeater的model添加数据 (2019-01-30 23:12) 

老铁有没有demo来一个
离线solo_wang

只看该作者 3楼 发表于: 2019-01-31
// 用Repeator的model添加数据还是不行,Column的布局还是没有生效~~~
Item {
    id:root
    RadioButton{
        text:"测试一行"

    }

}
// main.qml
ApplicationWindow{
    id:root
    height:640
    width:480
    visible:true
    title:"测试"
    property variant arr: []  // 存每个动态增加Item,并且作为repeator的model
    function add(){
        var component = Qt.createComponent("test.qml");
        if (component.status == Component.Ready) {
           var button = component.createObject(column); //column作为父组件
           arr.push(button)  // 保存新实例化的item
        }else{
             console.log("Component.Error: ",component.errorString());
        }

    }

    Column{
        id:column
        spacing:10
        Repeator{
           id:repeator
           model:arr
        }
    }
    Button{
       id:button
       anchors{bottom:parent.bottom;bottomMargin:10;}
       height:30;width:45;
       onClicked:
           add()

    }

    

}
离线ch781609892

只看该作者 4楼 发表于: 2019-04-24
test.qml中的Item给一个width和height即可
快速回复
限100 字节
 
上一个 下一个