2014-02-19 103 views
1

我QtQuick 1.0
我使用下面的代碼:無法訪問QML變量/ ID全球

Rectangle { 
    Component { 
     id: appDelegate 
     MouseArea{ 
      id:myMouseArea 
      hoverEnabled: true 
      onClicked:{ 
       onClicked: load.source = page;      
      } 
     } 
     Loader { 
      id: load 
     } 
    } 
    GridView { 
     id: view 

     // I am unable to access myMouseArea here. 
     highlight: myMouseArea.containsMouse ? appHighlight : !appHighlight 
     delegate: appDelegate 
    } 
} 

它給了我下面的錯誤:

ReferenceError: Can't find variable: myMouseArea /usr/lib/i386-linux-gnu/qt4/bin/qmlviewer exited with code 0

我不知道我提供的細節是否足夠,請讓我知道如果我缺少其他東西。

我使用此代碼爲例:
http://docs.knobbits.org/qt4/declarative-modelviews-gridview-qml-gridview-example-gridview-example-qml.html

+0

打消了我的答案,因爲這個問題被修改,它不再適用。 – Matthew

回答

2

,因爲它代表上下文中創建的,則不能訪問myMouseArea。您不能訪問currentItem以外的代表。但您可以在代表的上下文內自由訪問view,將currentIndex設置爲附加屬性index

這是一個糾正代碼:

Rectangle { 
    width: 360 
    height: 360 

    Component { // It must be a component, if we want use it as delegate 
     id: appDelegate 

     // its not possible to have more than one element inside component 
     Rectangle 
     { 
      // need to set size of item, anchors wont work here 
      // could use view.cellWidth and view.cellHeight to keep it DRY 
      width: 96 
      height: 66 

      color: "green" // color only to see the place of MouseArea 

      MouseArea { 
       id:myMouseArea 
       anchors.fill: parent // this setup the size to whole rectangle 
       // it this item have the size 0,0 it will simple do not work 
       hoverEnabled: true 

       onEntered: { 
        // we know the mouse is inside this region 
        // setting this value will show the highlight rectangle 
        view.currentIndex = index; 
       } 

       onClicked:{ 
        onClicked: load.source = page; 
       } 

      } 
      Loader { 
       // this is not needed but it's wise to not keep zero size 
       anchors.fill: parent 
       id: load 
      } 
     } 
    } 
    GridView { 
     id: view 

     // the size of GridView must be set, 
     // as otherwise no delegate will not show 
     anchors.fill: parent 
     anchors.margins: 5 

     cellWidth: 100 
     cellHeight: 70 

     // Rectangle will act as a border. 
     // Size and position is set by GridView 
     // to the size and position of currentItem. 
     // This is no a item, this makes a Component 
     // as highlight property needs one. 
     // You can create a Component like appDelegate. 
     highlight : Rectangle { 
      border.width: 2 
      border.color: "blue" 
     } 

     // some ListModel to setup the page variable inside delegate context 
     model: ListModel { 
      ListElement { page: "test1.qml"; } 
      ListElement { page: "test2.qml"; } 
      ListElement { page: "test3.qml"; } 
     } 

     delegate: appDelegate 
    } 
} 
+0

非常感謝。正在努力做到這一點。它的工作非常好! – Jino