使用鼠标QML绘制矩形

时间:2014-09-12 13:47:45

标签: qt qml waveform

我正在使用QML 2.0创建波形。 我想知道如何在用户点击波形时绘制矩形,并在用户释放鼠标按钮时结束。

我需要像黄色矩形一样的东西。

我尝试使用Canvas但是没有正常工作。 你能救我吗?

Canvas {
    property int prevX
    property int prevY
    property int hh:wave.height
    property int lineWidth: 2
    property color drawColor: "red"
    id:mycanvas

    height: 200
    width: 2000
    MouseArea {
        id:mousearea
        anchors.fill: parent
        cursorShape:Qt.PointingHandCursor
        onPositionChanged: mycanvas.requestPaint();

        onPressed: {
            prevX = mouse.x;
            prevY = mouse.y
            var mousePosition = mouse.x / mousearea.width;
            wave.zoomOut(mousePosition);
            console.log("QML: ZoomStart mousePosition " + mousePosition)

        }

        onReleased: {
            var mousePosition = mouse.x / mousearea.width;
            console.log("QML: ZoomFinish mousePosition " + mousePosition)
            wave.zoomOut2(mousePosition);
        }
    }

    onPaint: {
        var ctx = getContext('2d');
        ctx.beginPath();
        ctx.fillStyle = "#000000"
        ctx.globalAlpha = 0.05

        ctx.fillRect(prevX, 0, mousearea.mouseX-prevX,mainRectangle.height/4.5);

        ctx.stroke();
        ctx.restore();
    }
}

enter image description here

1 个答案:

答案 0 :(得分:2)

我要做的是动态实例化QtQuick Rectangle并同时设置其视觉属性:

只要把它作为你的波形图的一个孩子即可。组件:

MouseArea {
    id: selectArea;
    anchors.fill: parent;
    onPressed: {
        if (highlightItem !== null) {
            // if there is already a selection, delete it
            highlightItem.destroy (); 
        }
        // create a new rectangle at the wanted position
        highlightItem = highlightComponent.createObject (selectArea, {
            "x" : mouse.x 
        });
        // here you can add you zooming stuff if you want
    }
    onPositionChanged: {
        // on move, update the width of rectangle
        highlightItem.width = (Math.abs (mouse.x - highlightItem.x));  
    }
    onReleased: {
        // here you can add you zooming stuff if you want
    }

    property Rectangle highlightItem : null;

    Component {
        id: highlightComponent;

        Rectangle {
            color: "yellow";
            opacity; 0.35;
            anchors {
                top: parent.top;
                bottom: parent.bottom;
            }
        }
    }
}

这应该可以做到!