首页 文章

QML - 如何拖动ToolButton?

提问于
浏览
0

QT文档有tutorial .

我最初完全遵循它,它的工作原理 . 然后我做了两个修改:

  • 我用一个GridView(没有#2工作)替换了ListView .

  • 我试图在Rectangle“content”中向我的委托添加一个ToolButton,如下所示:


Rectangle {
    id: content

    ToolButton {
        id: toolButton
        icon.color = "transparent"
        icon.source = "image://Loader/iconName"
    }
    Drag.active: dragArea.held
    Drag.source: dragArea
    Drag.hotSpot.x: width / 2
    Drag.hotSpot.y: height / 2
}

这不起作用,ToolButton似乎正在处理鼠标移动而不传播消息(我可以点击按钮,但我不能拖动它)?这实际上有点预期是诚实的 .

所以说,有没有人有一个很好的方法来拖动ToolButtons?或者只是接受你不能这样做?我尝试了各种Rectangles和MouseAreas的组合,但我似乎无法在不打破另一个的情况下做一个(即拖动失败或按钮失败) .

1 回答

  • 0

    您可以将 MouseArea 作为 ToolButton 的子项移动以使用 pressAndHold 管理拖动,并传播单击以保持按钮行为:

    Rectangle {
        id: content
    
        ToolButton {
            id: toolButton
    
            // bind the visual state of the button to the MouseArea
            background: Rectangle {
                color: marea.pressed
                       ? Qt.darker("blue")
                       : marea.containsMouse
                         ? Qt.lighter("blue")
                         : "blue" // use your desired colors
            }
    
            MouseArea {
                id: marea
    
                property bool held: false
    
                drag.target: held ? content : undefined
                drag.axis: Drag.YAxis
    
                anchors.fill: parent
                hoverEnabled: true
                onPressAndHold: held = true
                onReleased: held = false
                onClicked: toolButton.clicked() // propagate clicked event to the ToolButton
            }
        }
        // ...
    }
    

相关问题