Qt 如何在QML 5.2中使用JavaScript访问一个按钮内部的buttonStyle对象

Qt 如何在QML 5.2中使用JavaScript访问一个按钮内部的buttonStyle对象,qt,qml,Qt,Qml,以下是我的Qml代码: Button { id: newMenu anchors { top: topMenu.top topMargin: 15 left: topMenu.left leftMargin: 16 } text: "New" iconSource: "../images/New.png" MouseArea { id: mouseArea

以下是我的Qml代码:

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 outpu总是

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

如何使用JavaScript获取元素?或者我们是否有其他方法在输入鼠标时更改背景颜色。

回答您的问题,您应该定义公共属性,如:

Button {
    id: root

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

    MouseArea { id: mousearea; ... }

    style: ButtonStyle {
        background: Rectanlge { color: root.backgroundColor; ... }
    }
}
然后使用is属性覆盖默认实现

但是,

您试图以完全错误的方式使用样式<代码>样式是
控件
状态的可视化表示,不应在运行时手动更改。因此,一种合适的方法是将控件属性绑定到样式(例如,使用属性)


通过在按钮内嵌套一个矩形,然后使用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; 
 }
结果是这样的:

为什么使用tt1而不是buttonStyle?这是否会引发类似的引用错误?@LaszloPapp是的,它会输出qrc:/qmls/menu。qml:40:ReferenceError:buttonStyle未定义HI。我不确定这是否是您想要的,但您可以使用“control”简单地更改按钮样式的背景色,例如:color:control.pressed?“#f00”:(control.hovered | | control.activeFocus?”#0f0:“#00f”)
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; 
 }