2016-10-18 102 views
0

我有2個qml文件。從另一個QML設置QML屬性

我想從第一個qml文件設置第二個qml fromperty。

**first.qml** 

var cmponent = Qt.createComponent("second.qml"); 
    var newObj = cmponent.createObject(swipeView); 
    newObj.pageIndex = i; 
    swipeView.insertItem(swipeView.currentIndex+i,newObj) 

並插入到SwipeView中。

其中'pageIndex'是2nd qml的整數屬性。 在第二個qml文件中,我有一個帶有單元格的GridLayout。 我需要顯示在此基礎上動態pageIndex財產

second.qml單元格內容

申報財產。

property int pageIndex: 0 
    onPageIndexChanged:{ 
     console.log("onPageIndexChanged :" +pageIndex) 
     home_grid.update() 

    } 

onPageIndexChanged方法被觸發,但是,我想根據屬性值設置網格單元格。

問題是 ,同時組件的初始化

var cmponent = Qt.createComponent("second.qml"); 

將細胞加載到GridLayout的。

我該如何發佈/解決此問題。

+1

1:爲什麼用JS函數創建對象? 2:你的GridLayout在哪裏?你想在那裏展示的細胞是什麼?你不能用索引作爲模型的GridView嗎? – derM

+0

1.我想動態創建視圖。基於ListModel計數。每個視圖都有具有最大元素6的網格。示例:模型包含7個元素,然後在firstView中顯示6個元素,並使用swipeView切換這些視圖,其餘1個顯示在sendView上。 2.「GridLayout」在另一個qml文件(second.qml)中。網格中的每個單元格/元素都基於模型的值顯示。 –

+0

應該可以在多個視圖中使用一個'ListModel'。所以我會建議使用'GridView'而不是'GridLayout'。然後你可以在這個'GridView'的委託中使用'magic'變量'index'來達到你的目的。 – derM

回答

0

我想你想要的是這樣的:

(我用我的例子爲你的拳頭問題) 應該說明我的意見。 當然你可以把不同的視圖放在不同的文件中。創建對象時,只需將相同的模型傳遞給兩者。

ListModel { 
    id: lm 
    ListElement { width: 40; height: 40 } 
    [...] 
    ListElement { width: 40; height: 40 } 
} 

SwipeView { 
    width: 200 
    height: 800 
    clip: true 
    currentIndex: 0 

    Repeater { 
     model: Math.ceil(lm.count/6) 
     delegate:   ListView { 
      width: 200 
      height: 800 
      property int viewIndex: index 
      model: DelegateModel { 
       model: lm 
       groups: DelegateModelGroup { name: 'filter' } 
       Component.onCompleted: { 
        for (var i = viewIndex * 6; i < lm.count && i < (viewIndex * 6) + 6; i++) { 
         items.setGroups(i, 1, ['items', 'filter']) 
        } 
       } 

       filterOnGroup: 'filter' 

       delegate: Rectangle { 
        width: 180 
        height: 30 
        border.width: 1 
        Text { 
         anchors.centerIn: parent 
         text: index 
        } 
       } 
      } 
     } 
    } 
} 

GridView { 
    clip: true 
    x: 300 
    width: 600 
    height: 600 
    model: lm 

    delegate: TestObj { 
    } 
} 

下面是代表TestObj

Rectangle { 
    width: model.width 
    height: model.height 
    property alias text: myText.text 
    Text { 
     id: myText 
     anchors.centerIn: parent 
     text: index 
    } 
} 

當然,你也可以這樣寫代碼:

delegate: TestObj { 
     width: model.width; height: model.height; text: index 
    } 

這將減少你的第二個QML-文件的相關性。

+0

在GridItem中,我必須顯示很多項目並基於某些條件條件。因此,我爲Grid Item創建了單獨的QML。 –

+0

這取決於你。正如你看到的,我也是這樣做的,用TestObj.qml – derM