2017-06-06 56 views
0

請有人解釋我一件事。假設我有一個項目,如果我點擊它,那麼會出現一個下拉菜單。當你將鼠標懸停在菜單項上時,如何做到這一點?QML MenuItem突出顯示不起作用

代碼:

Rectangle { 
    id: main_window 
    width: 600 
    height: 600 
    property int mrg: 10 

    Rectangle { 
     anchors.centerIn: parent 
     width: 500 
     height: 500 
     color: 'green' 

     Text { 
      id: field 
      text: "Click!" 
      font.pointSize: 20 
      color: 'white' 
      anchors.centerIn: parent 

      MouseArea { 
       id: ma 
       anchors.fill: parent 
       hoverEnabled: true 

       onClicked: { 
        menu.x = ma.mouseX 
        menu.open() 
       } 
      } 

      Menu { 
       id: menu 
       y: field.height 
       MenuItem { 
        text: "Menu item" 
        highlighted: true 

       } 
      } 
     } 
    } 
} 

在本文檔中,我碰到了合適的highlight負責選擇相應的菜單項的地步。我將它安裝在True中,但它沒有改變任何東西。 請告訴我我做錯了什麼。非常感謝。

回答

1

MenuItem默認實現不包括任何視覺高亮顯示功能,但可以作爲Qt manuals解釋圖形表示適應您的需求。所以,你的MenuItem應該是這樣的:

MenuItem { 
    id: control 
    text: "Menu item" 

    background: Item { 
     implicitWidth: 200 
     implicitHeight: 40 

     Rectangle { 
      anchors.fill: parent 
      anchors.margins: 1 
      color: control.highlighted ? "blue" : "transparent" // blue background if the control is highlighed 
      MouseArea { 
       anchors.fill: parent 
       hoverEnabled: true // enable mouse enter events when no mouse buttons are pressed 
       onContainsMouseChanged: control.highlighted = containsMouse // set the highlighted flag when the mouse hovers the MenuItem 
      } 
     } 
    } 
} 

注意,這個實現是基於Qt提供的default implementation

background: Item { 
    implicitWidth: 200 
    implicitHeight: 40 

    Rectangle { 
     x: 1 
     y: 1 
     width: parent.width - 2 
     height: parent.height - 2 
     color: control.visualFocus || control.down ? Default.delegateColor : "transparent" 
    } 
} 
+0

非常感謝您的幫助。是工作! –

相關問題