2014-01-08 25 views
5

下面是我的代碼設爲Qml:如何訪問按鈕樣式對象使用JavaScript一個按鈕裏面QML 5.2

Button { 
    id: newMenu 

    anchors { 
     top: topMenu.top 
     topMargin: 15 
     left: topMenu.left 
     leftMargin: 16 
    } 

    text: "New" 
    iconSource: "../images/New.png" 

    MouseArea { 
     id: mouseArea 
     anchors.fill: parent 
     hoverEnabled: true   //this line will enable mouseArea.containsMouse 
     onClicked: { 
      newProjectFileDlg.visible = true 
     } 
     onEntered: { 
      console.log(tt1); 
     } 
    } 

    style: ButtonStyle { 
     id: buttonStyle 
     background: Rectangle { 
      id: tt1 
      implicitWidth: 100 
      implicitHeight: 25 
      border.width: 0 
      radius: 4 
      color: mousearea.entered ? "lightsteelblue" : "#2e2e2e" 
     } 
    } 

我要訪問此按鈕的樣式屬性,改變background.color當鼠標懸停是。但console.log輸出總是

qrc:/qmls/menu.qml:40: ReferenceError: tt1 is not defined 

如何使用JavaScript獲取元素?或者我們有其他的方法來改變輸入鼠標的背景顏色。

+0

你爲什麼要使用TT1,而不是按鈕樣式?這是否會引發類似的ReferenceError? – lpapp

+0

@LaszloPapp是的,它輸出qrc:/qmls/menu.qml:40:ReferenceError:buttonStyle沒有定義 –

+0

嗨。我不確定是否你正在尋找,但你可以簡單地使用「控制」來改變ButtonStyle的背景顏色,就像這樣: color:control.pressed? 「#f00」:(control.hovered || control.activeFocus?「#0f0」:「#00f」) – deste

回答

4

回答你的問題,你應該定義公共財產,如:

Button { 
    id: root 

    property color backgroundColor: pressed ? 'skyblue' 
              : mousearea.entered ? "lightsteelblue" 
                   : "#2e2e2e" 
    ... 

    MouseArea { id: mousearea; ... } 

    style: ButtonStyle { 
     background: Rectanlge { color: root.backgroundColor; ... } 
    } 
} 

,然後採用的是屬性覆蓋默認的實現。

但是,

您試圖以完全錯誤的方式使用樣式。 StyleControl狀態的直觀表示,不應在運行時手動更改。因此,正確的方法是將控件屬性綁定到樣式(例如,使用屬性control)。

style: ButtonStyle { 
    background: Rectangle { 
     color: control.hovered ? 'lightsteelblue' 
           : 'skyblue' 
    } 
} 
1

可以實現不使用樣式通過嵌套按鈕內一個矩形,然後使用onHoveredChanged屬性來修改不透明度類似的東西。下面是一個例子。我這樣做是爲了避免與正常的按鈕樣式的懸停效果相沖突。

Button { 
    text: "Push me" 
    Rectangle{ 
     id: myRectId 
     anchors.fill: parent 
     anchors.margins: 1 
     color: "green" 
     opacity : .2 
    } 
    onHoveredChanged: hovered ? myRectId.opacity = 0 : myRectId.opacity = .2; 
} 

這結束這樣看: Example of QML button with different background color