2011-09-22 40 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; 
     } 
    } 
} 

我希望它能帮助你!