如何在Qt快速QML代码中动态地在网格布局中添加子项



我想在运行时添加控件,例如将一定数量的TextField项添加到GridLayout中。我尝试在下面的代码中使用Repeater(为简洁起见,跳过了一些代码)。

import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
Rectangle {
    width: 400
    height: 400
    GridLayout {
        id : gridmain
        Repeater {
            id:gridgenerate
            TextField{
                id:leditfill
                font.pointSize: 10
                placeholderText: index +1
                focus: true;
            }
        }
    }
}

Repeater通过 JS 函数填充:

function gameview() {
    console.log("grid")
    gridmain.rows = 10
    gridmain.columns = 10
    gridgenerate.model = gridmain.rows * gridmain.columns
    gridgenerate.forceActiveFocus()
}

这是正确的方法吗?如何专注于Gridlayout的前TextField

快完成了。删除gridgenerate.forceActiveFocus()并将"文本字段焦点"属性设置为 true(如果它是第一项):index == 0

GridLayout {
  id : gridmain
  Repeater {
    id:gridgenerate
    TextField{
        id:leditfill
        font.pointSize: 10
        placeholderText: index +1
        focus: index == 0 // only first item get focus
    }
}

这是一个很好的赞美诗。你可以做(像网格视图)

function gameview() {
    console.log("grid")
    gridgenerate.model = 0 //destroy all items created by repeater
    gridmain.rows = 10
    gridmain.columns = 10
    gridgenerate.model =  buttonModel.count //add new items, using ListModel
}

ListModel {
    id:buttonModel
    ListElement {
        color: "red"
        cols:2
        rows:2
        name: "B1"
    }
}
    Repeater {
          id:gridgenerate
          property var listobjects:[]
          Rectangle{
              id:button
              color :buttonModel.get(index).color
            }
        }

相关内容

  • 没有找到相关文章

最新更新