I am working on an QML program in which I change the color and the border color of a polygon painted on a Canvas. I have 2 buttons that change the colors, ie. 1 button making the border color red and the other one blue.
My problem is that each time I change the color set, the border of the polygon seems "corrupted", such as the used border colors mixed with each other. The drawn polygon is being resized each time I resize the window. So when I resize, its being repainted I believe. The colors are getting fixed at that point.
My question is: is there a way to disable the overlapping or is there a way to manually force the redrawing of all Canvases in the project?
Ucolors.qml:
import QtQuick 2.9
/**
* #brief Holds the color parameters of the whole UI
*
*/
Item
{
property var canvas
property var text
property var spiderBckgrnd
property var spiderLines
}
main.qml
Ucolors
{
id: colDay
canvas: "#eaedf1"
text: "#0e0e12"
spiderBckgrnd: "#f7fbff"
spiderLines: "#C8CBD0"
}
Ucolors
{
id: colNight
canvas: "#22212c"
text: "#ffffff"
spiderBckgrnd: "#0e0e12"
spiderLines: "#3C3C3F"
}
property var colGlob: colDay
Button
{
id: btn1
anchors.left: parent.left
text: "button1"
onClicked:
{
colGlob = colNight;
}
}
Button
{
id: btn2
anchors.left: btn1.right
text: "button2"
onClicked:
{
colGlob = colDay;
}
}
Then in the code colors are set like this: some_property: colGlob.spiderLines
If you do not explicitely call clearRect() on the context object of your Canvas, any drawing is painted on the existing content.
Since you're drawing a polygon, some antialiasing pixels are added on the edges to get smooth lines. Those pixels are semi-transparent, so when you draw the same polygon over the existing one with another color, color blending occurs on the edges; hence the "corrupted" appearance.
When you change the height or width of the canvas, the context is implicitely cleared, so the "corrupted" edge disappears.
An easy fix is to call clearRect in the onPaint handler of your Canvas.
Canvas
{
id: canvas
onPaint: {
var ctx = getContext("2d")
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height)
// Draw anything you want
...
}
}
Here is a small example that reproduces your problem, and show how it is fixed by calling clearRect
import QtQuick 2.10
import QtQuick.Window 2.10
import QtQuick.Controls 2.3
import QtQuick.Layouts 1.3
ApplicationWindow {
id: root
visible: true
width: 400
height: 200
property string color: "red"
onColorChanged: {
canvas.requestPaint()
}
ColumnLayout
{
anchors.fill: parent
anchors.margins: 20
spacing: 20
RowLayout
{
Layout.alignment: Qt.AlignHCenter
Repeater
{
model: ["red", "blue", "yellow"]
Button
{
text: modelData
highlighted: root.color == modelData
onClicked: {
root.color = modelData
}
}
}
CheckBox
{
id: clearBeforeRepaintCb
text: "Clear before paint"
}
}
Canvas
{
id: canvas
Layout.fillHeight: true
Layout.fillWidth: true
onPaint: {
var ctx = getContext("2d")
if(clearBeforeRepaintCb.checked)
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.strokeStyle = root.color
ctx.lineWidth = 10
ctx.beginPath()
ctx.moveTo(10, height/2)
ctx.lineTo(width-10, height/2+3)
ctx.stroke()
}
}
}
}
Related
I have a Component for an sddm theme. At the moment I use the theme dark sugar as the base theme. The component looks like the following:
Item {
id: hexagon
property color color:"yellow"
property int radius: 30
//layer.enabled: true
//layer.samples: 8
Shape {
//... Here some Positioning and other Stuff
ShapePath {
//... Here some Options and Pathlines
}
}
}
This works fine, but as soon as I uncomment both layer settings the component disappears. Does this happen, because I load the component like this:
Pane {
...
Item {
...
MyComponent {
z: 1
}
}
}
Nor the Pane or the Item use layer but most Components in the Item use the z: 1 property.
As iam_peter says, the default width and height properties of any Item are 0, and layer.enabled sets the size of the offscreen texture to the item size. By default, the scene graph doesn't do any clipping: a child item can populate scene graph nodes outside its parent's bounds. But when you confine the children's rendering to a specific offscreen texture, anything that doesn't fit is clipped. Here's a more interactive example to play with this:
import QtQuick
import QtQuick.Controls
Rectangle {
width: 640
height: 480
Column {
CheckBox {
id: cbLE
text: "layer enabled"
}
Row {
spacing: 6
TextField {
id: widthField
text: layerItem.width
onEditingFinished: layerItem.width = text
}
Label {
text: "x"
anchors.verticalCenter: parent.verticalCenter
}
TextField {
id: heightField
text: layerItem.height
onEditingFinished: layerItem.height = text
}
}
}
Rectangle {
id: layerItem
x: 100; y: 100
border.color: "black"; border.width: 2
layer.enabled: cbLE.checked
Rectangle {
width: 100
height: 100
color: "tomato"
opacity: 0.5
}
Text {
text: "this text will get clipped even when layer size is defined"
}
}
}
You can use renderdoc to see how the rendering is done; for example you can see the texture that is created by enabling the layer.
This is a small reproducible example:
import QtQuick
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Item {
//width: 200
//height: 200
//layer.enabled: true
Rectangle {
width: 100
height: 100
color: "red"
}
}
}
I suspect that if you don't set a size on the Item on which you want to enable the layer (layer.enabled: true), it will have a size of 0. Hence the offscreen buffer has a size of 0.
As a side note, this works without layer, because the clip property of an Item by default is set to false. So it won't clip to the bounds of its parent.
I have a toolbar that can be moved (by drag). Depending on the context the content of this toolbar will change, and its size will change accordingly.
My problem is, when the size is changing, the top-left position remains the same and the right border is moving (default and normal behaviour). But I want the top-right position to remain the same and the left border to move instead.
From screen 1 to 2 the toolbar gets smaller, and is shown like the blue rectangle. I want it to be placed like the red rectangle.
How can I achieve this ? Without anchoring on the right of the screen, because the toolbar is movable.
The first thing that comes to mind would be to wrap the toolbar in an Item, and anchor the toolbar to the top right of the item.
import QtQuick 2.8
import QtQuick.Controls 2.3
ApplicationWindow {
id: window
width: 800
height: 800
visible: true
Slider {
id: slider
value: 200
to: 400
}
Item {
x: 600
ToolBar {
id: toolBar
anchors.top: parent.top
anchors.right: parent.right
implicitWidth: slider.value
MouseArea {
anchors.fill: parent
drag.target: toolBar.parent
}
}
}
}
The Item doesn't render anything itself, and has a "zero" size so that the ToolBar is anchored correctly.
Edit: thanks to #GrecKo for coming up with the MouseArea idea. :) This allows you to drag the ToolBar.
A simple solution is to readjust the position of the item when the width changes:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
Window {
visible: true
width: 640
height: 480
Slider {
id: slider
value: 200
to: 400
}
Rectangle {
id: block
color: "red"
width: parseInt(slider.value)
height:50
x: 100
y: 50
readonly property int previousWidth: width
onWidthChanged: {
block.x += previousWidth - width
}
MouseArea {
anchors.fill: parent
drag.target: block
}
}
}
Since onWidthChanged is called before the previousWidth property change, you can easily adjust the x position from previous and new width values.
(Edit: improved my example using #Mitch Slider)
You can do that with Behavior and PropertyAction.
This relies on the feature that you can specify the point in a Behavior when its linked property actually change. You can then add some logic before and after this effective change:
import QtQuick 2.8
import QtQuick.Controls 2.3
ApplicationWindow {
id: window
width: 800
height: 800
visible: true
Slider {
id: slider
value: 200
to: 400
}
Rectangle {
id: rect
width: slider.value
y: 40
height: 40
color: "orange"
Behavior on width {
id: behavior
property real right
SequentialAnimation {
ScriptAction { script: behavior.right = rect.x + rect.width } // the width of the rectangle is the old one
PropertyAction { } // the width of the rectangle changes at this point
ScriptAction { script: rect.x = behavior.right - rect.width } // the width of the rectangle is the new one
}
}
MouseArea {
anchors.fill: parent
drag.target: parent
}
}
}
Consider the QML code below, which allows me to insert points onto a blank QML canvas, with mouse-clicks and then clear all the input points and the corresponding pictures on the canvas, using a button placed in the upper-left hand corner
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window{
id: root
width: 640
height: 480
visible: true
Canvas {
id: mycanvas
width: 1000
height: 1000
property var arrpoints : []
onPaint: {
var context = getContext("2d");
// Delete everything drawn before?
context.clearRect(0, 0, mycanvas.width, mycanvas.height);
// Render all the points as small black-circles
context.strokeStyle = Qt.rgba(0, 1, 1, 0)
// Draw all the points
for(var i=0; i < arrpoints.length; i++){
var point = arrpoints[i]
context.ellipse(point["x"], point["y"], 10, 10)
context.fill()
context.stroke()
}
}
// For mousing in points.
MouseArea {
id: mymouse
anchors.fill: parent
onClicked: {
// Record mouse-position into all the input objects
mycanvas.arrpoints.push({"x": mouseX, "y": mouseY})
mycanvas.requestPaint()
console.log( mycanvas.arrpoints )
} // onClicked
}// MouseArea
} // Canvas
Button {
text: "clear input"
onClicked: {
mycanvas.arrpoints.length = 0
mycanvas.requestPaint()
console.log( mycanvas.arrpoints )
}
}
}//Window
This code behaves quite strangely. Suppose I input a few points onto the canvas, and then click the "clear input" button. then as expected all the pictures (ie little circles corresponding to points) vanish from the canvas
and the arrpoints array is set to empty.
But when I start clicking on the canvas again, the cleared pictures are redrawn, alongside the new points being entered!! Why should this be? After printing to the console, I can still see arrpoints=[] so the problem should be with the clearing of the canvas in the onPaint section.
How do I tell QML to erase its canvas memory completely?
If you want to clean the Canvas you must reset the context. In this case, implement a function that does it and force the canvas to update.
import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window{
id: root
width: 640
height: 480
visible: true
Canvas {
id: mycanvas
width: 1000
height: 1000
property var arrpoints : []
onPaint: {
var context = getContext("2d");
// Delete everything drawn before?
context.clearRect(0, 0, mycanvas.width, mycanvas.height);
// Render all the points as small black-circles
context.strokeStyle = Qt.rgba(0, 1, 1, 0)
// Draw all the points
for(var i=0; i < arrpoints.length; i++){
var point = arrpoints[i]
context.ellipse(point["x"], point["y"], 10, 10)
context.fill()
context.stroke()
}
}
function clear() {
var ctx = getContext("2d");
ctx.reset();
mycanvas.requestPaint();
}
// For mousing in points.
MouseArea {
id: mymouse
anchors.fill: parent
onClicked: {
// Record mouse-position into all the input objects
mycanvas.arrpoints.push({"x": mouseX, "y": mouseY})
mycanvas.requestPaint()
console.log( mycanvas.arrpoints )
} // onClicked
}// MouseArea
} // Canvas
Button {
text: "clear input"
onClicked: {
mycanvas.arrpoints.length = 0
mycanvas.clear()
console.log( mycanvas.arrpoints )
}
}
}//Window
I am a QML / Javascript noob, and would like some help with that.
I want to insert some points (represented as small black circles) onto a white QML canvas element and then run an algorithm on them (such as finding convex hulls via an external geometric library)
Here is my QML code.
import QtQuick 2.5
import QtQuick.Window 2.2
Window{
id: root
width: 640
height: 480
visible: true
Canvas {
width: 1000
height: 1000
onPaint: {
var context = getContext("2d");
}
MouseArea {
id: mymouse
anchors.fill: parent
property var arrpoints : []
onClicked: {
// Record mouse-position
arrpoints = arrpoints.concat([mouseX, mouseY])
console.log(arrpoints)
}
}
}
}
So far the above code, opens up a window, with a QML canvas on it, and can keep track of the positions on the canvas (via the array arrpoints) where I single-clicked with my mouse, and outputs the array of clicked-points to the console.
But now, everytime the arrpoints changes, how do I 'tell' QML to draw a small black circle at that point immediately?
I would have thought the onPaint part of QML would trigger the rendering of the new state immediately, but it seems that part is only for the initial drawing on the canvas, before the user starts interacting with it.
You have to call the canvas requestPaint() function to force the painting. It is also advisable to save the data of the positions appropriately: {"x": x_value, "y": y_value}
import QtQuick 2.5
import QtQuick.Window 2.2
Window{
id: root
width: 640
height: 480
visible: true
Canvas {
id: canvas
width: 1000
height: 1000
onPaint: {
var context = getContext("2d")
context.strokeStyle = Qt.rgba(0, 0, 0, 1)
context.lineWidth = 1
for(var i=0; i < mymouse.arrpoints.length; i++){
var point = mymouse.arrpoints[i]
context.ellipse(point["x"]-5, point["y"]-5, 10, 10)
}
context.stroke()
}
MouseArea {
id: mymouse
anchors.fill: parent
property var arrpoints : []
onClicked: {
arrpoints.push({"x": mouseX, "y": mouseY})
canvas.requestPaint()
}
}
}
}
The example below illustrates my problem.
I create a small Rectangle at the top left and clicking on it toggles the color between red and green.
Next, I create a StackView and I push a Rectangle to the StackView and bind the color of this second Rectangle to the color of the top-left rectangle
Expected behavior would be that, clicking on the top-left Rectangle would also change the color of the Rectangle on the StackView since the color was binded. Unfortunately, this is not the case.
Note that things work fine when pushing stackRect2 to the stack (see line in comment)
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
id: mainWindow
visible: true
width: 1280
height: 720
Rectangle {
id: rect
width: 100
height: 100
focus: true
color: toggle? "red":"green"
property var toggle:false;
MouseArea {
anchors.fill: parent
onClicked: rect.toggle = !rect.toggle
}
}
StackView {
id: stack
width: 100
height:100
anchors.left: rect.right
anchors.leftMargin: 10
Component.onCompleted: {
stack.push ({item:stackRect, properties: {color:rect.color}})
//stack.push ({item:stackRect2})
}
}
Component {
id:stackRect
Rectangle {}
}
Component {
id:stackRect2
Rectangle {color:rect.color}
}
}
Apparently, this behavior is expected behavior and is in line with Component::createObject().
Using
stack.push (stackRect, {color:Qt.binding(function() { return rect.color})})
works just fine.