Can someone help me to understand behaviour of this code? I wrote simple example of side panel menu (just template now) and there is problem to use onMenuVisibleChanged slot (but all I need actually works, just want to understand why another way don't). Logically it should change x of panel rectangle to specified values, but it didn't. Please help me ot understand correct approach for this thing.
main.qml
import QtQuick 2.3
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
menuBar: MenuBar{
Menu{
title: "File"
MenuItem{
text: "Exit"
onTriggered: Qt.quit()
}
}
}
SidePane{
id: sidePane
menuWidth: 350
z: 2
}
}
SidePane.qml
import QtQuick 2.3
import QtQuick.Window 2.2
Item {
id: screenItem
anchors.fill: parent
function show() {
rect.x = 0
menuVisible = true
}
function hide() {
rect.x = -rect.width
menuVisible = false
}
property int animationDuration: 200
property bool menuVisible: false
property int dragThreshold: 120
property int menuWidth: 300
Rectangle {
id: rect
width: menuWidth
x: -rect.width
height: Screen.height
color: "lightsteelblue"
Drag.active: menuDragArea.drag.active
Behavior on x {
NumberAnimation {
duration: animationDuration
easing.type: Easing.InOutQuad
}
}
MouseArea {
property int dragX: 0
property int startX: 0
property int diffX: 0
id: menuDragArea
hoverEnabled: true
height: rect.height
width: rect.width + 40
anchors.left: rect.left
drag.target: rect
drag.axis: Drag.XAxis
drag.minimumX: -rect.width
drag.maximumX: 0
onPressed: startX = rect.x + rect.width
onReleased: {
dragX = rect.x + rect.width
diffX = Math.abs(startX - dragX)
if ((diffX > dragThreshold) && (startX == 0)){
rect.x = 0
menuVisible = true
} else if ((diffX < dragThreshold) && (startX == 0)){
rect.x = -rect.width
menuVisible = false
}
if ((diffX > dragThreshold) && (startX == rect.width)){
rect.x = -rect.width
menuVisible = false
} else if ((diffX < dragThreshold) && (startX == rect.width)){
rect.x = 0
menuVisible = true
}
}
}
}
Rectangle{
id: shadowRect
anchors.left: rect.right
anchors.right: screenItem.right
opacity: (rect.x + rect.width) / (rect.width * 2.2)
color: "black"
height: screenItem.height
MouseArea{
id: shadowArea
anchors.fill: shadowRect
visible: menuVisible ? true : false
hoverEnabled: true
onClicked: {
if (menuVisible == true){
rect.x = -rect.width
menuVisible = false
}
}
}
Rectangle{
id: shadowRect2
color: "black"
anchors.left: parent.left
width: 5
opacity: (rect.x + rect.width) / (rect.width * 2)
height: screenItem.height
}
Rectangle{
id: shadowRect3
color: "black"
anchors.left: parent.left
width: 3
opacity: (rect.x + rect.width) / (rect.width * 1.9)
height: screenItem.height
}
}
onMenuVisibleChanged: menuVisible ? rect.x = 0 : rect.x = -rect.width
}
Appreciate any help. Just a QML beginner. The most purpose is to use this panel in android application. Feel free to use this code if you want.
The property drag make the x value draggable
if you implement it by mouseX onPressed/onReleased, rect.x will be 0 or -rect.width onMenuVisibleChanged
MouseArea {
property int dragX: 0
property int startX: 0
property int diffX: 0
id: menuDragArea
hoverEnabled: true
height: rect.height
width: rect.width + 40
anchors.left: rect.left
onPressed: {
startX = mouseX;
console.log(rect.x)
}
onReleased: {
diffX = Math.abs(startX - mouseX)
console.log("diff:"+diffX)
if ((diffX > dragThreshold) && (mouseX > startX) && (rect.x !=0 )){
rect.x = 0
menuVisible = true
} else if ((diffX > dragThreshold) && (mouseX < startX) && (rect.x == 0)){
rect.x = -rect.width
menuVisible = false
}
}
}
with visual drag ,sorry it's ugly:
MouseArea {
property int startX: 0
property int diffX: 0
property int startRectX: 0
property bool isPressed: false
id: menuDragArea
hoverEnabled: true
height: rect.height
width: rect.width + 40
anchors.left: rect.left
onPressed: {
startX = mouseX;
startRectX = rect.x
isPressed = true
console.log(rect.x)}
onMouseXChanged: {
if(isPressed)
rect.x = (mouseX>rect.width)? 0 : (mouseX-rect.width)
}
onReleased: {
isPressed = false
diffX = Math.abs(startX - mouseX)
console.log("diff:"+diffX)
if ((mouseX >= startX) && (startRectX == -rect.width )){
if(diffX > dragThreshold)
{
rect.x = 0
menuVisible = true
}
else
rect.x = startRectX
} else if ((mouseX <= startX) && (startRectX == 0)){
if(diffX > dragThreshold)
{
rect.x = -rect.width
menuVisible = false
}
else
rect.x = startRectX
}
else
rect.x = startRectX
}
}
Related
UPDATE 1 - i can get it to work using Javascript - but that seems to be a little bit unoptimized (from 2-3% to 30% load with qmlscene.exe when activated) - complete recreation when the model changes (its not ever growing), is that the only way or is there a more "declarative" style available?
How can i add a PathLine to a ShapePath based on a Model?
i know how to use a Repeater from outside of Items but not how to implode them inside of Items
do i need some sort of Repeater-Delegate on pathElements?
and i don't want to use the LineSeries component
import QtQuick.Shapes 1.15
import QtQuick 2.15
Shape {
ListModel {
id: myPositions
ListElement { x: 0; y:38 }
ListElement { x: 10; y: 28 }
ListElement { x: 20; y: 30 }
ListElement { x: 30; y: 14 }
}
ShapePath {
strokeColor: "black"
strokeWidth: 1
fillColor: "transparent"
startX: 0
startY: 0
PathLine { x: 0; y: 38 }
PathLine { x: 10; y: 28 }
PathLine { x: 20; y: 30 }
PathLine { x: 30; y: 14 }
// Repeater {
// model: myPositions
// PathLine { x: model.x; y: model.y }
// }
}
}
UPDATE 1
import QtQuick.Shapes 1.15
import QtQuick 2.15
Shape {
ListModel {
id: myPositions
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Timer
{
interval: 100
running: true
repeat: true
property real myX: 0
onTriggered: {
myPositions.append({"x":myX, "y":getRandomInt(0,30)})
myX = myX + 10
}
}
function createPathLineElements(positionsModel, shapePath)
{
var pathElements = []
for (var i = 0; i < positionsModel.count; i++)
{
var pos = myPositions.get(i)
var pathLine = Qt.createQmlObject('import QtQuick 2.15; PathLine {}',
shapePath);
pathLine.x = pos.x
pathLine.y = pos.y
pathElements.push(pathLine)
}
return pathElements
}
ShapePath {
id: myPath
strokeColor: "black"
strokeWidth: 1
fillColor: "transparent"
startX: 0
startY: 0
pathElements: createPathLineElements(myPositions, myPath)
}
}
Use an Instantiator:
Shape {
ListModel {
id: myPositions
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Timer {
interval: 100
running: true
repeat: true
property real myX: 0
onTriggered: {
myPositions.append({"x":myX, "y":getRandomInt(0,30)})
myX = myX + 10
}
}
ShapePath {
id: myPath
fillColor: "transparent"
strokeColor: "red"
capStyle: ShapePath.RoundCap
joinStyle: ShapePath.RoundJoin
strokeWidth: 3
strokeStyle: ShapePath.SolidLine
}
Instantiator {
model: myPositions
onObjectAdded: myPath.pathElements.push(object)
PathLine {
x: model.x
y: model.y
}
}
}
You can't use repeater in that element.
The most performant way is to use QQuickItem in order to create a custom Item which draws incremental path.
Yet another simpler ways are:
1- Use PathSvg element and set its path runtime like below:
ShapePath {
fillColor: "transparent"
strokeColor: "red"
capStyle: ShapePath.RoundCap
joinStyle: ShapePath.RoundJoin
strokeWidth: 3
strokeStyle: ShapePath.SolidLine
PathSvg { id: ps; path: parent.p } //<== fill path property using js
property string p: ""
Component.onCompleted: {
for ( var i = 0; i < myModel.count; i++) {
p += "L %1 %2".arg(myModel.get(i).x).arg(myModel.get(i).y);
}
ps.path = p;
}
}
2- If you know steps, so you can pre-declare all PathLines and then set their values runtime. Just like a heart rate line on a health care monitor.
My program is starting by default in windowed mode.
My problem is if I start it and then press on maximize, then on minimize and then click on it in the taskbar, it is in windowed mode and not maximized.
To be honest I made that whole new window because I like programs that have a nice clear design. I don't know if you can change the top of a normal Window like the icon of the close button or the color of it.
main.qml:
/***********************************************************************************************************/
/*********************************************** S T A R T *************************************************/
/***********************************************************************************************************/
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
import QtGraphicalEffects 1.0
import QtQuick.Controls.Universal 2.0
import QtQuick.Controls.Imagine 2.3
import QtQuick.Controls.Material 2.0
import QtQuick.Dialogs.qml 1.0
import QtQuick.Extras 1.4
import QtQuick.Templates 2.5
import QtQuick.LocalStorage 2.0
ApplicationWindow {
id: mainWindow
visible: true
width: 900
height: 600
title: qsTr("Test")
color: "#2F3136"
flags: Qt.Window | Qt.FramelessWindowHint
property int _max: 0
property int _min: 0
property int _resizeRightVar: 0
property int _resizeLeftVar: 0
property int _resizeTopVar: 0
property int _resizeBottomVar: 0
property bool _resizeRight: true
property bool _resizeLeft: true
property bool _resizeTop: true
property bool _resizeBottom: true
property int _rRCursor: Qt.SizeHorCursor
property int _rLCursor: Qt.SizeHorCursor
property int _rTCursor: Qt.SizeVerCursor
property int _rBCursor: Qt.SizeVerCursor
property bool _moveWindow: true
property int previousX
property int previousY
///////////////////////////////////////////////////////////
/// TOP RECTANGLE WITH TITLE, MINIMIZE, MAXIMIZE, CLOSE ///
///////////////////////////////////////////////////////////
Rectangle {
id: rectangle
width: parent.width
height: 23
color: "#202225"
anchors.top: parent.top
//////////////////////////////////
/// TITLE IN THE TOP RECTANGLE ///
//////////////////////////////////
Text {
leftPadding: 6
topPadding: 1
opacity: 0.75
text: mainWindow.title
font.pixelSize: 14
font.family: "Dodge"
color: "white"
}
///////////////////////////////////////
/// MOUSE AREA IN THE TOP RECTANGLE ///
///////////////////////////////////////
MouseArea {
anchors.fill: parent
enabled: mainWindow._moveWindow
onPressed: {
previousX = mouseX
previousY = mouseY
}
onMouseXChanged: {
var dx = mouseX - previousX
mainWindow.setX(mainWindow.x + dx)
}
onMouseYChanged: {
var dy = mouseY - previousY
mainWindow.setY(mainWindow.y + dy)
}
onDoubleClicked: {
//mainWindow.visibility = "Maximized"
mainWindow._max ++
if(mainWindow._max == 1){
mainWindow.visibility = "Maximized"
//mainWindow.showMaximized()
mainWindow._moveWindow = false
mainWindow._rRCursor = Qt.ArrowCursor
mainWindow._rLCursor = Qt.ArrowCursor
mainWindow._rTCursor = Qt.ArrowCursor
mainWindow._rBCursor = Qt.ArrowCursor
mainWindow._resizeRight = false
mainWindow._resizeLeft = false
mainWindow._resizeTop = false
mainWindow._resizeBottom = false
} else if(mainWindow._max == 2){
mainWindow.visibility = "Windowed"
//mainWindow.showNormal()
mainWindow._max = 0
mainWindow._moveWindow = true
mainWindow._rRCursor = Qt.SizeHorCursor
mainWindow._rLCursor = Qt.SizeHorCursor
mainWindow._rTCursor = Qt.SizeVerCursor
mainWindow._rBCursor = Qt.SizeVerCursor
mainWindow._resizeRight = true
mainWindow._resizeLeft = true
mainWindow._resizeTop = true
mainWindow._resizeBottom = true
}
}
}
/////////////////////////////////////////
/// CLOSE BUTTON IN THE TOP RECTANGLE ///
/////////////////////////////////////////
Rectangle {
id: close_window
width: 27
height: 22.5
anchors.top: parent.top
anchors.topMargin: 0
anchors.right: parent.right
anchors.rightMargin: 0
color: "#202225"
Image {
id: closeImage
source: "close_window.png"
anchors.fill: parent
opacity: 0.6
fillMode: Image.PreserveAspectFit
}
MouseArea {
id: close_windowMouseArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
mainWindow.close()
}
onEntered: {
cursorShape: Qt.PointingHandCursor
close_window.color = "#F04747"
closeImage.opacity = 1
}
onExited: {
cursorShape: Qt.ArrowCursor
close_window.color = "#202225"
closeImage.opacity = 0.6
}
}
}
////////////////////////////////////////////
/// MAXIMIZE BUTTON IN THE TOP RECTANGLE ///
////////////////////////////////////////////
Rectangle {
id: maximize_window
width: 27
height: 22.5
anchors.top: parent.top
anchors.topMargin: 0
anchors.right: parent.right
anchors.rightMargin: 29
color: "#202225"
Image {
id: maximizeImage
source: "maximize_window.png"
anchors.fill: parent
opacity: 0.6
fillMode: Image.PreserveAspectFit
}
MouseArea {
id: maximize_windowMouseArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
mainWindow._max ++
if(mainWindow._max == 1){
mainWindow.visibility = "Maximized"
//mainWindow.showMaximized()
mainWindow._moveWindow = false
mainWindow._rRCursor = Qt.ArrowCursor
mainWindow._rLCursor = Qt.ArrowCursor
mainWindow._rTCursor = Qt.ArrowCursor
mainWindow._rBCursor = Qt.ArrowCursor
mainWindow._resizeRight = false
mainWindow._resizeLeft = false
mainWindow._resizeTop = false
mainWindow._resizeBottom = false
} else if(mainWindow._max == 2){
mainWindow.visibility = "Windowed"
//mainWindow.showNormal()
mainWindow._max = 0
mainWindow._moveWindow = true
mainWindow._rRCursor = Qt.SizeHorCursor
mainWindow._rLCursor = Qt.SizeHorCursor
mainWindow._rTCursor = Qt.SizeVerCursor
mainWindow._rBCursor = Qt.SizeVerCursor
mainWindow._resizeRight = true
mainWindow._resizeLeft = true
mainWindow._resizeTop = true
mainWindow._resizeBottom = true
}
}
onEntered: {
maximize_window.color = "#2B2D30"
maximizeImage.opacity = 1
}
onExited: {
maximize_window.color = "#202225"
maximizeImage.opacity = 0.6
}
}
}
////////////////////////////////////////////
/// MINIMIZE BUTTON IN THE TOP RECTANGLE ///
////////////////////////////////////////////
Rectangle {
id: minimize_window
width: 27
height: 22.5
anchors.top: parent.top
anchors.topMargin: 0
anchors.right: parent.right
anchors.rightMargin: 57
color: "#202225"
Image {
id: minimizeImage
source: "minimize_window.png"
anchors.fill: parent
opacity: 0.6
fillMode: Image.PreserveAspectFit
}
MouseArea {
id: minimize_windowMouseArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
mainWindow._min ++
if(mainWindow._min >= 1){
mainWindow._min = 0
//mainWindow.showMinimized()
mainWindow.visibility = "Minimized"
//if(mainWindow._max == 1){
// mainWindow.showMaximized()
// mainWindow.visibility = "Maximized"
//}
}
}
onEntered: {
minimize_window.color = "#2B2D30"
minimizeImage.opacity = 1
}
onExited: {
minimize_window.color = "#202225"
minimizeImage.opacity = 0.6
}
}
}
}
///////////////////////////
/// RIGHT RESIZE WINDOW ///
///////////////////////////
MouseArea {
id: rightResize
width: 5
enabled: mainWindow._resizeRight
cursorShape: mainWindow._rRCursor
anchors {
right: parent.right
top: parent.top
bottom: parent.bottom
}
onEntered: {
if(mainWindow._resizeRight == true){
mainWindow._rRCursor = Qt.SizeHorCursor
} else if(mainWindow._resizeRight == false){
mainWindow._rRCursor = Qt.ArrowCursor
}
}
onPressed: previousX = mouseX
onMouseXChanged: {
var dx = mouseX - previousX
mainWindow.setWidth(parent.width + dx)
}
}
//////////////////////////
/// LEFT RESIZE WINDOW ///
//////////////////////////
MouseArea {
id: leftResize
width: 5
enabled: mainWindow._resizeLeft
cursorShape: mainWindow._rLCursor
anchors {
left: parent.left
top: parent.top
bottom: parent.bottom
}
onEntered: {
if(mainWindow._resizeLeft == true){
mainWindow._rLCursor = Qt.SizeHorCursor
} else if(mainWindow._resizeLeft == false){
mainWindow._rLCursor = Qt.ArrowCursor
}
}
onPressed: previousX = mouseX
onMouseXChanged: {
var dx = mouseX - previousX
mainWindow.setX(mainWindow.x + dx)
mainWindow.setWidth(mainWindow.width - dx)
}
}
/////////////////////////
/// TOP RESIZE WINDOW ///
/////////////////////////
MouseArea {
id: topResize
height: 5
enabled: mainWindow._resizeTop
cursorShape: mainWindow._rTCursor
anchors {
top: parent.top
left: parent.left
right: parent.right
}
onEntered: {
if(mainWindow._resizeTop == true){
mainWindow._rTCursor = Qt.SizeVerCursor
} else if(mainWindow._resizeTop == false){
mainWindow._rTCursor = Qt.ArrowCursor
}
}
onPressed: previousY = mouseY
onMouseYChanged: {
var dy = mouseY - previousY
mainWindow.setY(mainWindow.y + dy)
mainWindow.setHeight(mainWindow.height - dy)
}
}
////////////////////////////
/// BOTTOM RESIZE WINDOW ///
////////////////////////////
MouseArea {
id: bottomResize
height: 5
enabled: mainWindow._resizeBottom
cursorShape: mainWindow._rBCursor
anchors {
bottom: parent.bottom
left: parent.left
right: parent.right
}
onEntered: {
if(mainWindow._resizeBottom == true){
mainWindow._rBCursor = Qt.SizeVerCursor
} else if(mainWindow._resizeBottom == false){
mainWindow._rBCursor = Qt.ArrowCursor
}
}
onPressed: previousY = mouseY
onMouseYChanged: {
var dy = mouseY - previousY
//mainWindow.setY(mainWindow.y + dy)
mainWindow.setHeight(mainWindow.height + dy)
}
}
////////////////////////////
/// TEXT INPUT IN MIDDLE ///
////////////////////////////
Rectangle{
id: textInputBG
}
}
/***********************************************************************************************************/
/************************************************** E N D **************************************************/
/***********************************************************************************************************/
Here's a hacky way to solve this:
Add property int saved_state to your ApplicationWindow
Then add the following code:
onVisibilityChanged: {
if(saved_state === 4 && visibility === 2) {
showMaximized()
saved_state = -1
}
}
Then isnide your MouseArea minimize_sindowMouseArea add the following line:
saved_state = mainWindow.visibility //NEW LINE
mainWindow.visibility = "Minimized" //Existing line
Explanation: Save the state of your window right before you minimize, then restore it to the save_state when restored.
I don't know of any cleaner way, but that should do it :)
In this simple code, the user can drag the racket up or downwards. We want to know the time for the racket movement (i.e, each y changes of the racket caught by onYChanged) . If the user moves it fast the time for each y change is littler than the time they move it slowly, naturally.
I went for this, but it always writes "Time = 0"! Is there any way for doing this simple task please?
main.qml:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
id: window
visible: true
width: 700; height: 500
color: "gray"
Rectangle {
id: table
width: window.width / 1.15; height: window.height / 1.15
y: 10
anchors.horizontalCenter: parent.horizontalCenter
color: "royalblue"
}
Racket {
id: racket
x: table.width - 10
y: table.height / 2
}
}
Racket.qml:
import QtQuick 2.12
Rectangle {
width: 15; height: 65
property int oldY: y
property bool yUwards: false
property bool yDwards: false
property double colTime
onYChanged: {
colTime = new Date().getTime()
if (y > oldY)
yDwards = true
else if (y < oldY)
yUwards = true
oldY = y
console.log("Time = ", colTime - new Date().getTime())
}
MouseArea {
anchors.fill: parent
anchors.margins: -parent.height
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: table.y
drag.maximumY: table.height - parent.height + 10
}
}
If you want to measure the change time, you must do the same procedure as with Y, save the last time in memory:
import QtQuick 2.12
Rectangle {
width: 15; height: 65
property bool yUwards: false
property bool yDwards: false
property real oldY: y
property double last_time: new Date().getTime()
onYChanged: {
var current_time = new Date().getTime()
console.log("Time = ", current_time - last_time)
if (y > oldY)
yDwards = true
else if (y < oldY)
yUwards = true
oldY = y
last_time = current_time
}
MouseArea {
anchors.fill: parent
anchors.margins: -parent.height
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: table.y
drag.maximumY: table.height - parent.height + 10
}
}
I have a Canvas with the image, that I load via filedialog, how can I get the pixel array of this image?
I need convert it to grayscale by converting every pixel using formula and load it back to the Canvas.
Here the code:
import QtQuick 2.0
import QtQuick.Controls 2.1
import QtQuick.Controls.Material 2.1
import QtQuick.Layouts 1.2
import QtQuick.Dialogs 1.0
ApplicationWindow {
id: window
visible: true
width: 1000
height: 750
Material.theme: Material.Dark
Material.background: "#2C303A"
Material.accent: "#65B486"
Material.foreground: "#efefef"
GridLayout {
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.margins: 9
columns: 4
rows: 3
rowSpacing: 10
columnSpacing: 10
Canvas {
id: canvas
height: window.height - 15
Layout.columnSpan: 4
Layout.fillWidth: true
property bool loaded: false
property var filepath: ''
onDrawChanged: requestPaint()
onFilepathChanged: {
loadImage(filepath)
}
onImageLoaded: {
loaded = true
requestPaint()
}
onPaint: {
if (loaded) {
var ctx = getContext("2d");
ctx.drawImage(filepath, 0, 0, width, height)
}
if (to_grayscale) {
var ctx = getContext("2d");
var ar = ctx.getImageData(0, 0, width, height).data
for(var i in ar){
print(i)
}
}
}
}
FileDialog {
id: fileDialog
title: "Please choose a file"
nameFilters: ["Image files (*.jpg *.png *.jpeg)"]
onAccepted: {
console.log("You chose: " + fileDialog.fileUrls)
canvas.filepath = fileDialog.fileUrls
canvas.requestPaint()
}
onRejected: {
console.log("Canceled")
}
}
Drawer {
id: drawer
visible: true
modal: false
width: 0.33 * window.width
height: window.height
GridLayout {
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.margins: 9
columns: 2
rows: 3
rowSpacing: 10
columnSpacing: 10
Button {
text: 'Load image'
onClicked: fileDialog.visible = true
}
Button {
text: 'RGB to Grayscale'
onClicked: canvas.draw = true
}
}
}
}
}
I'm trying to get ImageData, but here's empty
I read that Canvas contain PixelArray, but I don't know how to get it.
Thank you.
To access the rgba values
var ar = ctx.getImageData(0, 0, width, height);
for( var x=0; x < ar.data.length; x=x+4 )
{
// To read RGBA values
var red = ar.data[x];
var green = ar.data[x + 1];
var blue = ar.data[x + 2];
var alpha = ar.data[x + 3];
console.log(red + ", " + green + ", " + blue + ", " + alpha );
// To convert to grey scale, modify rgba according to your formula
ar.data[x] = 0.2126 *ar.data[x] + 0.7152* ar.data[x+1] + 0.0722 *ar.data[x+2];
ar.data[x+1] = 0.2126 *ar.data[x] + 0.7152* ar.data[x+1] + 0.0722 *ar.data[x+2];
ar.data[x+2] = 0.2126 *ar.data[x] + 0.7152* ar.data[x+1] + 0.0722 *ar.data[x+2];
ar.data[x+3] = 255;
}
// update the canvas with new data
ctx.drawImage(ar.data, 0, 0);
You have to requestPaint() in onClicked slot of Button
In a touchpanel application, is it possible to edit the integer value of a qml SpinBox, from QtQuickControls 2.0, in such a way that a numeric keypad appears on-screen and one can enter the exact value?
Or do you have any idea on how to embed this predefined number pad in a customized spinbox, that should pop-up when the user taps on the integer number?
The numpad can be set to be invisible and put on top of everything, then you can have a function to enable its visibility and set it's target. When you are done with typing the number, you set the target value to the numpad value, and hide it again. This way you can target different spinboxes.
As of the actual method to request the keypad, you can put a MouseArea to fill the spinbox on top of it. Or you can make the mouse area narrower, so that the plus/minus buttons of the spinbox are still clickable.
Also keep in mind that numpad you have linked is not actually functional.
Thanks for your suggestion. I came up with a first quick solution based on your idea and the number pad from the example section. I post it here, just in case it helps someone else as starting point. I am a QML beginner, so happy to get any improvements or corrections.
See attached screenshot of the numeric virtual touchpad appearing when clicking on the spinbox number
SpinBox {
id: boxCommPos
x: 50
y: 50
z: 0
width: 200
height: 50
to: 360
editable: false
contentItem: TextInput {
z: 1
text: parent.textFromValue(parent.value, parent.locale)
font: parent.font
//color: "#21be2b"
//selectionColor: "#21be2b"
//selectedTextColor: "#ffffff"
horizontalAlignment: Qt.AlignHCenter
verticalAlignment: Qt.AlignVCenter
readOnly: !parent.editable
validator: parent.validator
inputMethodHints: Qt.ImhFormattedNumbersOnly
}
Label {
id: commUnits
x: 125
y: 0
z: 3
text: qsTr("º")
font.pointSize: 16
anchors.right: parent.right
anchors.rightMargin: 45
}
MouseArea {
id: padCommPos
x: 40
y: 0
z: 2
width: parent.width-x-x
height: 50
onClicked: touchpad.visible=true
}
}
NumberTouchpad {
id: touchpad
x: 470
y: -20
z: 1
scale: 0.90
visible: false
Rectangle {
id: backrect
x: -parent.x/parent.scale
z: -1
width: parent.parent.width/parent.scale
height: parent.parent.height/parent.scale
color: "#eceeea"
opacity: 0.5
MouseArea {
anchors.fill: parent
}
}
}
The file NumberPad.qml
import QtQuick 2.0
Grid {
columns: 3
columnSpacing: 32
rowSpacing: 16
signal buttonPressed
Button { text: "7" }
Button { text: "8" }
Button { text: "9" }
Button { text: "4" }
Button { text: "5" }
Button { text: "6" }
Button { text: "1" }
Button { text: "2" }
Button { text: "3" }
Button { text: "0" }
Button { text: "."; dimmable: true }
//Button { text: " " }
Button { text: "±"; color: "#6da43d"; operator: true; dimmable: true }
//Button { text: "−"; color: "#6da43d"; operator: true; dimmable: true }
//Button { text: "+"; color: "#6da43d"; operator: true; dimmable: true }
//Button { text: "√"; color: "#6da43d"; operator: true; dimmable: true }
//Button { text: "÷"; color: "#6da43d"; operator: true; dimmable: true }
//Button { text: "×"; color: "#6da43d"; operator: true; dimmable: true }
Button { text: "C"; color: "#6da43d"; operator: true }
Button { text: "✔"; color: "#6da43d"; operator: true; dimmable: true }
Button { text: "X"; color: "#6da43d"; operator: true }
}
Display.qml
// Copyright (C) 2015 The Qt Company Ltd.
import QtQuick 2.0
import QtQuick.Window 2.0
Item {
id: display
property real fontSize: Math.floor(Screen.pixelDensity * 10.0)
property string fontColor: "#000000"
property bool enteringDigits: false
property int maxDigits: (width / fontSize) + 1
property string displayedOperand
property string errorString: qsTr("ERROR")
property bool isError: displayedOperand === errorString
function displayOperator(operator)
{
listView.model.append({ "operator": operator, "operand": "" })
enteringDigits = true
listView.positionViewAtEnd()
//console.log("display",operator);
}
function newLine(operator, operand)
{
displayedOperand = displayNumber(operand)
listView.model.append({ "operator": operator, "operand": displayedOperand })
enteringDigits = false
listView.positionViewAtEnd()
//console.log("newLine",operator);
}
function appendDigit(digit)
{
if (!enteringDigits)
listView.model.append({ "operator": "", "operand": "" })
var i = listView.model.count - 1;
listView.model.get(i).operand = listView.model.get(i).operand + digit;
enteringDigits = true
listView.positionViewAtEnd()
//console.log("num is ", digit);
}
function setDigit(digit)
{
var i = listView.model.count - 1;
listView.model.get(i).operand = digit;
listView.positionViewAtEnd()
//console.log("setDigit",digit);
}
function clear()
{
displayedOperand = ""
if (enteringDigits) {
var i = listView.model.count - 1
if (i >= 0)
listView.model.remove(i)
enteringDigits = false
}
//console.log("clearing");
}
// Returns a string representation of a number that fits in
// display.maxDigits characters, trying to keep as much precision
// as possible. If the number cannot be displayed, returns an
// error string.
function displayNumber(num) {
if (typeof(num) != "number")
return errorString;
var intNum = parseInt(num);
var intLen = intNum.toString().length;
// Do not count the minus sign as a digit
var maxLen = num < 0 ? maxDigits + 1 : maxDigits;
if (num.toString().length <= maxLen) {
if (isFinite(num))
return num.toString();
return errorString;
}
// Integer part of the number is too long - try
// an exponential notation
if (intNum == num || intLen > maxLen - 3) {
var expVal = num.toExponential(maxDigits - 6).toString();
if (expVal.length <= maxLen)
return expVal;
}
// Try a float presentation with fixed number of digits
var floatStr = parseFloat(num).toFixed(maxDigits - intLen - 1).toString();
if (floatStr.length <= maxLen)
return floatStr;
return errorString;
}
Item {
id: theItem
width: parent.width
height: parent.height
Rectangle {
id: rect
x: 0
color: "#eceeea"
height: parent.height
width: display.width
}
/*Image {
anchors.right: rect.left
source: "images/paper-edge-left.png"
height: parent.height
fillMode: Image.TileVertically
}
Image {
anchors.left: rect.right
source: "images/paper-edge-right.png"
height: parent.height
fillMode: Image.TileVertically
}
Image {
id: grip
source: "images/paper-grip.png"
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
anchors.bottomMargin: 20
}*/
ListView {
id: listView
width: display.width
height: display.height
delegate: Item {
height: display.fontSize * 1.1
width: parent.width
Text {
id: operator
font.pixelSize: display.fontSize
color: "#6da43d"
text: model.operator
}
Text {
id: operand
y:5
font.pixelSize: display.fontSize
color: display.fontColor
anchors.right: parent.right
anchors.rightMargin: 22
text: model.operand
}
}
model: ListModel { }
}
}
}
calculator.qs
// Copyright (C) 2015 The Qt Company Ltd.
var curVal = 0
var memory = 0
var lastOp = ""
var previousOperator = ""
var digits = ""
function disabled(op) {
if (op == "✔")
display.fontColor="#000000"
if (op=="X")
return false
else if (op == "✔" && (digits.toString().search(/\./) != -1 || digits.toString().search(/-/)!= -1 || parseInt(digits)>359)) {
display.fontColor="#ff0000"
return true
}
else if (digits == "" && !((op >= "0" && op <= "9") || op == "."))
return true
else if (op == '=' && previousOperator.length != 1)
return true
else if (op == "." && digits.toString().search(/\./) != -1) {
return true
} else if (op == "√" && digits.toString().search(/-/) != -1) {
return true
} else {
return false
}
}
function digitPressed(op)
{
if (disabled(op))
return
if (digits.toString().length >= display.maxDigits)
return
if (lastOp.toString().length == 1 && ((lastOp >= "0" && lastOp <= "9") || lastOp == ".") ) {
digits = digits + op.toString()
display.appendDigit(op.toString())
} else {
digits = op
display.appendDigit(op.toString())
}
lastOp = op
}
function operatorPressed(op)
{
if (disabled(op))
return
lastOp = op
if (op == "±") {
digits = Number(digits.valueOf() * -1)
display.setDigit(display.displayNumber(digits))
return
}
if (previousOperator == "+") {
digits = Number(digits.valueOf()) + Number(curVal.valueOf())
} else if (previousOperator == "−") {
digits = Number(curVal.valueOf()) - Number(digits.valueOf())
} else if (previousOperator == "×") {
digits = Number(curVal) * Number(digits.valueOf())
} else if (previousOperator == "÷") {
digits = Number(curVal) / Number(digits.valueOf())
}
if (op == "+" || op == "−" || op == "×" || op == "÷") {
previousOperator = op
curVal = digits.valueOf()
digits = ""
display.displayOperator(previousOperator)
return
}
if (op == "=") {
display.newLine("=", digits.valueOf())
}
curVal = 0
previousOperator = ""
if (op == "1/x") {
digits = (1 / digits.valueOf()).toString()
} else if (op == "x^2") {
digits = (digits.valueOf() * digits.valueOf()).toString()
} else if (op == "Abs") {
digits = (Math.abs(digits.valueOf())).toString()
} else if (op == "Int") {
digits = (Math.floor(digits.valueOf())).toString()
} else if (op == "√") {
digits = Number(Math.sqrt(digits.valueOf()))
display.newLine("√", digits.valueOf())
} else if (op == "mc") {
memory = 0;
} else if (op == "m+") {
memory += digits.valueOf()
} else if (op == "mr") {
digits = memory.toString()
} else if (op == "m-") {
memory = digits.valueOf()
} else if (op == "backspace") {
digits = digits.toString().slice(0, -1)
display.clear()
display.appendDigit(digits)
} else if (op == "✔") {
window.visible=false
boxCommPos.value=parseInt(digits)
display.clear()
curVal = 0
memory = 0
lastOp = ""
digits = ""
} else if (op == "X") {
window.visible=false
display.clear()
curVal = 0
memory = 0
lastOp = ""
digits = ""
}
// Reset the state on 'C' operator or after
// an error occurred
if (op == "C" || display.isError) {
display.clear()
curVal = 0
memory = 0
lastOp = ""
digits = ""
}
}
Button.qml
// Copyright (C) 2015 The Qt Company Ltd.
import QtQuick 2.0
Item {
id: button
property alias text: textItem.text
property color color: "#eceeea"
property bool operator: false
property bool dimmable: false
property bool dimmed: false
width: 30
height: 50
Text {
id: textItem
font.pixelSize: 48
wrapMode: Text.WordWrap
lineHeight: 0.75
color: (dimmable && dimmed) ? Qt.darker(button.color) : button.color
Behavior on color { ColorAnimation { duration: 120; easing.type: Easing.OutElastic} }
states: [
State {
name: "pressed"
when: mouse.pressed && !dimmed
PropertyChanges {
target: textItem
color: Qt.lighter(button.color)
}
}
]
}
MouseArea {
id: mouse
anchors.fill: parent
anchors.margins: -5
onClicked: {
if (operator)
window.operatorPressed(parent.text)
else
window.digitPressed(parent.text)
}
}
function updateDimmed() {
dimmed = window.isButtonDisabled(button.text)
}
Component.onCompleted: {
numPad.buttonPressed.connect(updateDimmed)
updateDimmed()
}
}