2014-09-12 159 views
1

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

我需要类似黄色的矩形。

我尝试使用画布,但无法正常工作。 你能帮我吗?

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

+0

为什么它不能正常工作?它做错了什么? – Mitch 2014-09-12 14:18:51

+0

您的代码因错误而无法运行。请张贴一些事。 – Mitch 2014-09-12 14:37:46

+0

@Mitch你是在低调推荐新的QML提问者吗? ;) – mlvljr 2014-09-14 22:28:49

回答

1

我会做的就是实例化一个QtQuick矩形动态,并在同一时间设置它的视觉特性:

只是把这个障患儿你的“波形图”组成的:

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; 
      } 
     } 
    } 
} 

这应该做的伎俩!

+0

它的工作原理!万分感谢!!! – dominic 2014-09-17 06:52:49

+0

有用答案!!只是调整工作,如果你从右到左选择而不是从左到右! – Jimmy 2015-08-13 13:41:31

+0

@Jimmy:你是否介意在发布的代码中修复它?这将有助于其他人:) – Isaac 2016-08-15 00:41:55