PDA

View Full Version : QML: display an image onClicked



mohit_king
10th July 2011, 12:54
Hi, I am new to QML and so I am learning it by creating a simple tic tac toe game......

My problem is mentioned below:

I have used Grid to display all of the 9 rectangle blocks for tic tac toe game.....


Grid {
x: 22
y: 7
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
columns: 3
spacing: 3

Block11 {
id: block11
text: ""
MouseArea {
anchors.fill: parent
}
onClicked: [problem is here]

}
Block12 {...}
.
.
.
.
.
Block33{.....}



I have problem in the onClicked section. When user clicks anyone of these blocks then an image "x.png" should be displayed on that block, but i am unable to do so....

I,ve tried following:


Block11 {
id: block11
text: ""
MouseArea {
anchors.fill: parent
}
onClicked: Image{
source: "x.png"
anchors.centerIn: parent
}

but the above code gives an error.....i've also tried to find a way from many sites but was unsuccessful......please help.....

mushroom
10th July 2011, 17:27
You can't declare an Image element inside "onClicked". Declare it first inside the Block, give it an id, then in onClicked use the "opacity" or "visible" properties to hide/show the image. for example:



Item {
id: block

Image {
id: pic
source: "x.jpg"
visible: false //hidden by default
anchors.centerIn: parent
}

MouseArea {
anchors.fill: parent
onClicked: pic.visible = true
}
}

mohit_king
11th July 2011, 09:51
You can't declare an Image element inside "onClicked". Declare it first inside the Block, give it an id, then in onClicked use the "opacity" or "visible" properties to hide/show the image.

Hey this method works....but by using this i gotta load two images (x.png and zero.png) for each block and make visible whichever is appropritae.......dont u think this will make the app a bit slow.....

mushroom
12th July 2011, 15:02
Hey this method works....but by using this i gotta load two images (x.png and zero.png) for each block and make visible whichever is appropritae.......dont u think this will make the app a bit slow.....

In QML all the elements that are declared are loaded the first time the file is read, from top to bottom.
You can dynamically load elements using the Loader element apparently:
http://doc.qt.nokia.com/4.7-snapshot/qml-loader.html

I don't know about performance because i don't really know how it all works under the hood, but i doubt it's gonna slow your program down..