【问题标题】:Draw rectangle using mouse QML使用鼠标 QML 绘制矩形
【发布时间】:2014-09-12 13:47:45
【问题描述】:

我正在使用 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();
    }
}

【问题讨论】:

  • 为什么不能正常工作?它做错了什么?
  • 您的代码因错误而无法运行。请发布一些有用的东西。
  • @Mitch 您是否对新来的 QML 提问者投了反对票? ;)
  • @mlvljr,确实如此。在我开始投票之前,我只能问很多次。毕竟,这就是该功能的用途。至少我留下了一个理由;这里的大多数人只是投反对票,什么也没说。 :)
  • @Mitch 你是个残忍的朋友,Mitch!

标签: qt qml waveform


【解决方案1】:

我要做的是动态地实例化一个 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;
            }
        }
    }
}

这应该可以解决问题!

【讨论】:

  • 有用的答案!!如果您从右到左而不是从左到右选择,只需调整即可工作!
  • @Jimmy:你介意在发布的代码中修复它吗?这对其他人会有所帮助:)
猜你喜欢
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
相关资源
最近更新 更多