2015-02-23 88 views
0

這是一些簡單的QML代碼,它包含一個Button和一個MouseArea。我想Button檢測到鼠標左鍵和右鍵點擊。QML MouseArea重疊其他小工具

Rectangle { 
    anchors.fill:parent; 
    width: 1302 
    height: 638 

    Button { 
     id: button1 
     x: 378 
     y: 332 
     width: 194 
     height: 66 
     text: qsTr("Button") 
    } 

    MouseArea { 
     id: mouseArea1 
     x: 368 
     y: 306 
     width: 226 
     height: 108 
     acceptedButtons: Qt.RightButton 
     propagateComposedEvents: true 
     onClicked: { 
      console.log("Click") 
      mouse.accepted = false 
     } 
    } 
} 

由於MouseArea定位在Button的頂部,我怎麼能強迫Button接受鼠標事件?

+0

「按鈕」中沒有任何點擊處理程序。你如何得到迴應?不要同時使用'anchors.fill'和'width' /'height'。如果你真的想重疊一個表面與另一個表面,使用'z'。而且據我所知'Button'不響應右鍵單擊。你究竟在這裏做什麼? – folibis 2015-02-23 22:43:08

+0

我想要在右鍵單擊某個按鈕時彈出一個上下文菜單。 – illunara 2015-02-24 03:01:37

+0

但更重要的是,當我們放在它們的頂部時(如tableView,textEditor .....),MouseArea會獲取其他小部件的所有mouseEvent。我如何解決它? – illunara 2015-02-24 03:20:25

回答

2

試試這個,如果我理解你:

import QtQuick 2.4 
import QtQuick.Window 2.2 
import QtQuick.Controls 1.2 


Window { 
    id: screen 
    width: 800 
    height: 600 
    visible: true 

    Button { 
     anchors.centerIn: parent 
     text: qsTr("Button") 
     onClicked: { 
      console.log("Button was clicked"); 
     } 
     z: 100 
     MouseArea { 
       anchors.fill: parent 
       acceptedButtons: Qt.RightButton 
       onClicked: { 
        console.log("Button right button was clicked"); 
        mouse.accepted = true 
       } 
      } 
    } 

    MouseArea { 
      anchors.fill: parent 
      acceptedButtons: Qt.RightButton 
      propagateComposedEvents: true 
      onClicked: { 
       console.log("Window right button was clicked") 
      } 
      z: 99 
     } 
} 

不過我建議你用普通方式來顯示按鈕彈出。使用Button.menu顯示下拉菜單按鈕。

+0

哦哇O_O我不知道Z-Depth是如何在qml中工作的。 這也適用於中繼器和代理商品嗎? – illunara 2015-02-24 04:11:33

+0

它會爲每個元素繼承'Item' – folibis 2015-02-24 04:13:09

+0

你能看看我的代碼嗎?將mouseArea放入其中時,我無法選擇tableView的項目。 https://gist.github.com/illunara/936367731e66db553ef0 – illunara 2015-02-24 04:25:12