2011-09-22 81 views
0

我在QT QML中製作了一個包含MouseArea元素的項目。Qt中MouseArea的網格QML

下面是代碼,

import QtQuick 1.0 
Rectangle { 
id: base 
width: 240 
height: 320 
x:0; y:0 
color: "#323138" 
/////////////////////// MAIN FOCUSSCOPE ////////////////////// 
FocusScope { 
    id: mainfocus 
    height: base.height; width: base.width 
    focus: true 
    /////////////////////// MAIN GRID /////////////////////////// 
    GridView { 
     id: maingrid 
     width: base.width-10; height: base.height-titlebar.height-10 
     x: 5; y: titlebar.height+5; 
     cellHeight: maingrid.height/3; cellWidth: maingrid.width/3-1 
     Component { 
      id: myicon 
      Rectangle { 
       id: wrapper 
       height: maingrid.cellHeight-10; width: maingrid.cellWidth-10 
       radius: 8; smooth: true 
       color: GridView.isCurrentItem ? "#c0d0c0" : "transparent" 
       focus: true 
       MouseArea { 
        id: clickable 
        anchors.fill: wrapper 
        hoverEnabled: true 
        //onClicked: func() 
       } 
       Image { 
        id: iconpic 
        source: "./ui6.svg" 
        anchors.centerIn: wrapper 
       } 
       Text { 
        id: iconname 
        color: wrapper.GridView.isCurrentItem ? "black" : "#c8dbc8" 
        anchors.top: iconpic.bottom; anchors.horizontalCenter: iconpic.horizontalCenter 
        text: name 
       } 
      } 
     } 
     model: 4 
     delegate: myicon 
     focus: true 
    } 
} 
//////////////////////// TITLEBAR /////////////////////// 
Rectangle { 
    id: titlebar 
    x:base.x 
    y:base.y 
    height: 25; width: base.width 
    color : "#356f47" 
    Text { 
     color: "#fdfdfd" 
     anchors.centerIn: titlebar 
     text: "title" 
    } 
} 
} 

我想做出這樣的項目的網格,以便它給了我,我創建了我可以使用不同的功能定製可點擊的項目的網格。

使用GridView元素,我能夠製作這樣一個網格,它使用我自定義項目的數量作爲模板。

問題是,當我點擊這些項目中的任何一個時,它會執行一個函數,因爲我的項目中只有一個MouseArea元素。我能夠檢測到對某個項目的點擊,但無法唯一確定點擊了哪個項目。我如何實現這一目標?

當然,我可能做錯了,所以其他建議也歡迎。 謝謝

回答

2

當GridView項目創建實例時,它們會繼承索引變量。這標識了獨特的項目。

MouseArea { 
    id: clickable 
    anchors.fill: wrapper 
    hoverEnabled: true 
    onClicked: { 
     maingrid.currentIndex=index; 

     switch (index) 
     { 
     case 0: 
      //Function or method to call when clicked on first item 
      break; 
     case 1: 
      //Function or method to call when clicked on second item 
      break; 
     default: 
      //Function or method to call when clicked on another item 
      break; 
     } 
    } 
} 

我希望它能幫助你!