我对QML很陌生,我正试图让QML Button
在事件发生时改变它的背景。 Button
使用style: ButtonStyle
和Canvas
生成一些图片(通过JavaScript)。我使用QML State
来控制Button
状态。
我发现Canvas
没有自动刷新,所以我试图在requestPaint()
处理程序中调用onStateChanged
,但是当定义它时,这个信号不知道如何到达画布在style
属性中。
这是我的代码:
Button {
id: small_rounded_button
state: "OFF"
states: [
State {
name: "ON"
PropertyChanges {
target: small_rounded_button
backgroundColor: "#18243C"
}
},
State {
name: "OFF"
PropertyChanges {
target: small_rounded_button
backgroundColor: "#aaa"
}
}
]
MouseArea {
anchors.fill: parent
onClicked: {
if (small_rounded_button.enabled == true)
{
if (small_rounded_button.state == "ON")
{
small_rounded_button.state = "OFF"
}
else
{
small_rounded_button.state = "ON"
}
}
}
}
style: ButtonStyle {
background: Item {
Canvas {
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.reset();
ctx.beginPath();
ctx.lineWidth = height * 0.1;
ctx.roundedRect(ctx.lineWidth / 2, ctx.lineWidth / 2,
width - ctx.lineWidth, height - ctx.lineWidth, small_rounded_button.radius, small_rounded_button.radius);
ctx.strokeStyle = "grey";
ctx.stroke();
/* this definitely sets the colour when app starts */
ctx.fillStyle = small_rounded_button.backgroundColor;
ctx.fill();
}
/* This never happens */
onStateChanged: {
requestPaint()
}
}
Label {
text: small_rounded_button.text
color: "#000"
font.pixelSize: small_rounded_button.height * 0.5
//anchors.centerIn: parent
}
label: null
}
}
}
提前感谢您的帮助,
格雷格
答案 0 :(得分:2)
您在onStateChanged
内部实施了Canvas
处理程序,该处理程序不会更改状态,但Button
会更改状态。
您可以使用信号和插槽存档您想要的内容:
Canvas {
Component.onCompleted: {
small_rounded_button.stateChanged.connect(requestPaint);
}
}
无论如何,您的代码中存在更多问题,这是一个正常运行的版本:
import QtQuick 2.0
import QtQuick.Controls 1.3
import QtQuick.Controls.Styles 1.3
Button {
id: small_rounded_button
property string backgroundColor : "#f0f"
state: "OFF"
states: [
State {
name: "ON"
PropertyChanges {
target: small_rounded_button
backgroundColor: "#18243C"
}
},
State {
name: "OFF"
PropertyChanges {
target: small_rounded_button
backgroundColor: "#aaa"
}
}
]
MouseArea {
anchors.fill: parent
onClicked: {
if (small_rounded_button.enabled == true)
{
if (small_rounded_button.state == "ON")
{
small_rounded_button.state = "OFF"
}
else
{
small_rounded_button.state = "ON"
}
}
}
}
style: ButtonStyle {
background: Item {
Canvas {
Component.onCompleted: {
requestPaint();
small_rounded_button.stateChanged.connect(requestPaint);
}
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.reset();
ctx.beginPath();
ctx.lineWidth = height * 0.1;
ctx.roundedRect(ctx.lineWidth / 2, ctx.lineWidth / 2,
width - ctx.lineWidth, height - ctx.lineWidth, small_rounded_button.radius, small_rounded_button.radius);
ctx.strokeStyle = "grey";
ctx.stroke();
/* this definitely sets the colour when app starts */
ctx.fillStyle = small_rounded_button.backgroundColor;
ctx.fillRect(0, 0, width, height);
}
}
Label {
text: small_rounded_button.text
color: "#000"
font.pixelSize: small_rounded_button.height * 0.5
//anchors.centerIn: parent
}
}
}
}