如何在Qt快速QML代码中动态添加gridlayout中的子项

时间:2015-01-22 05:40:32

标签: qt qml grid-layout qt-quick

我想在运行时添加控件,例如已将一定数量的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()
}

这是正确的做法吗?如何关注TextField的第一个Gridlayout

2 个答案:

答案 0 :(得分:1)

几乎完成了。删除gridgenerate.forceActiveFocus()并将 TextField 焦点属性设置为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
    }
}

答案 1 :(得分:0)

其'一个很好的方法。 你可以做它dinamicaly(像gridView)

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
            }
        }