[Solved] QML Button Color doesn't change when Button is Clicked
-
Hello everyone,
I have defined a custom button in QML, and it was changing the color when pressed, until I added a mouseArea, which onClicked calls a function. Then the color does not change anymore. However I can change the other parameter ie the radius.
Any ideas why this happens?
@Button {
id: "myButton";
text: "btnTxt";signal buttonClick(); onButtonClick: { console.log("Button "+ myButton.id +" is clicked!") } MouseArea { anchors.fill: parent onClicked: { myButton.buttonClick(); } } style: ButtonStyle { background: Rectangle { color: control.pressed ? "#336699" : "#0099FF"; radius: 1; } }
}@
-
A couple of things, first I'm not sure what code you had that worked so that makes it a little tougher to know exactly where you went wrong. Secondly, id's should not be quoted.In my Qt Creator the quoted id gets flagged as an error (but the code still runs). Third you don't have to add a signal/slot pair to handle the click but maybe you had other reasons for that. Fourth, myButton.id produced "undefined" in my tests.
The problem you're asking about appears to be your use of "control.pressed", what is "control"? Here is my rewrite and it works although not all these changes are needed. Notice I gave the mouse area an id and used that.
@Button {
id: myButton
text: "btnTxt";
function buttonClick()
{
console.log("Button "+ myButton.text +" is clicked!")
}MouseArea { id: myMouseId anchors.fill: parent onClicked: { myButton.buttonClick(); } } style: ButtonStyle { background: Rectangle { color: myMouseId.pressed ? "#336699" : "#0099FF"; radius: 1; } }
}@
-
-
Shameless Self Promotion: I just recently published a course on Pluralsight on "Qt Quick Fundamentals":http://bit.ly/qtquickfun. I think you would get a lot of benefit out of it. It's part 2 of a 3 part series on Qt (part 3 is in progress). Pluralsight is a subscription based site but I can get you started with a free week-long VIP pass. You can watch as many hours as you want for a week and download course materials and watch off-line. Our hope of course is you will find Pluralsight so addictive and valuable that you sign up for a subscription. My course will take 4.5 hours of your time but I suspect in the long run it will save you many more hours than that. At least that's my goal! Send me an email through the forum if you want the pass.