In all the previous examples of this chapter, we have discussed the methods and techniques used to render 2D graphics with Qt's C++ API. However, we have yet to learn how to achieve similar results using the powerful QML script.
In this project, we'll be do something quite different:
qml.qrc
from the Resource
folder in the project pane by right-clicking on it and selecting Open in Editor. Then, remove MainForm.ui.qml
from your project's resources, as we don't need it for this project:main.qml
, which is listed under qml.rc
in the project pane. After that, remove the entire section that references MainForm
. Now what is left is only the Window
object in main.qml
. After that, set an ID for the window and adjust its width and height to higher values, like so:import QtQuick 2.5 import QtQuick.Window 2.2 Window { id: myWindow visible: true width: 540 height: 380 }
Canvas
object under myWindow
and call it myCanvas
. After that, we make its width and height the same as myWindow
:Window { id: myWindow visible: true width: 540 height: 380 Canvas { id: myCanvas width: myWindow.width height: myWindow.height } }
onPaint
event is triggered; in this case, we will draw a cross on the window:Canvas { id: myCanvas width: myWindow.width height: myWindow.height onPaint: { var context = getContext('2d') context.fillStyle = 'white' context.fillRect(0, 0, width, height) context.lineWidth = 2 context.strokeStyle = 'black' // Draw cross context.beginPath() context.moveTo(50, 50) context.lineTo(100, 100) context.closePath() context.stroke() context.beginPath() context.moveTo(100, 50) context.lineTo(50, 100) context.closePath() context.stroke() } }
// Draw tick context.beginPath() context.moveTo(150, 90) context.lineTo(158, 100) context.closePath() context.stroke() context.beginPath() context.moveTo(180, 100) context.lineTo(210, 50) context.closePath() context.stroke()
// Draw triangle context.lineWidth = 4 context.strokeStyle = "red" context.fillStyle = "salmon" context.beginPath() context.moveTo(50,150) context.lineTo(150,150) context.lineTo(50,250) context.closePath() context.fill() context.stroke()
// Draw circle context.lineWidth = 4 context.strokeStyle = "blue" context.fillStyle = "steelblue" var pi = 3.141592653589793 context.beginPath() context.arc(220, 200, 60, 0, pi, true) context.closePath() context.fill() context.stroke() context.beginPath() context.arc(220, 280, 60, 0, 2 * pi, true) context.closePath() context.fill() context.stroke()
// Draw image context.drawImage("tux.png", 280, 10, 256, 297)
Canvas
object to ask QML to load the image file when the program is started, then call the requestPaint()
signal when the image is loaded so that the onPaint()
event slot will be triggered:Component.onCompleted: { loadImage("tux.png") } onImageLoaded:requestPaint(); onPaint: { // The code we added previously }
3.147.70.247