How to draw a polygon with QML ?
-
@clochydd said:
Hi,
AFAIK there's currently no QML type for drawing a polygon.
If it's not too complex, you may draw the polygon with a couple of rotated Rectangles or use a C++ Object.Thanks for your reply,
Alright, I have to display an ellipse but simulated with a polygon so I'm going to search on the C++ Object side.
Regards,
-
Hi! You can create your own QQuickPaintedItem derived class. You need to implement its
paint()
function. In this function you can use the QPainter API to draw polygon of your choice. Add properties withQ_PROPERTY
to hand over parameters to your object from the QtQuick side. -
@bam500 Another option, is to follow your first idea : using the Canvas.
Here is an example taken from the (excellent) Qt Cadaques book drawing a 4 sides polygon (ok let's call it a rectangle ;-) ) :Canvas { id: root // canvas size width: 200; height: 200 // handler to override for drawing onPaint: { // get context to draw with var ctx = getContext("2d") // setup the stroke ctx.lineWidth = 4 ctx.strokeStyle = "blue" // setup the fill ctx.fillStyle = "steelblue" // begin a new path to draw ctx.beginPath() // top-left start point ctx.moveTo(50,50) // upper line ctx.lineTo(150,50) // right line ctx.lineTo(150,150) // bottom line ctx.lineTo(50,150) // left line through path closing ctx.closePath() // fill using fill style ctx.fill() // stroke using line width and stroke style ctx.stroke() } }
-
Check the "Canvas element" in the Qt5_cadaques book:
http://qmlbook.github.io/en/ch07/index.html