Qt 无法访问的if语句,如何避免
我在Qt 5.9.4中有此代码:Qt 无法访问的if语句,如何避免,qt,qml,Qt,Qml,我在Qt 5.9.4中有此代码: ButtonStyle { padding.top: 0 padding.bottom: 0 padding.right: 0 padding.left: 0 background: Rectangle { implicitHeight: enableButton.height implicitWidth: enableButton.width color: {
ButtonStyle {
padding.top: 0
padding.bottom: 0
padding.right: 0
padding.left: 0
background: Rectangle {
implicitHeight: enableButton.height
implicitWidth: enableButton.width
color: {
if ((buttonEnabled || hoverAlways) && enabled) {
if (propertyButton.hovered)
hoveredBgColor
else
defaultBgColor
} else {
selectedBgColor
}
if (propertyButton.pressed)
selectedBgColor
}
}
}
我在Qt 5.11.2上收到以下警告:
无法将[undefined]分配给QColor
上述警告的解决方案是使用return
语句,如下所示:
ButtonStyle {
padding.top: 0
padding.bottom: 0
padding.right: 0
padding.left: 0
background: Rectangle {
implicitHeight: enableButton.height
implicitWidth: enableButton.width
color: {
if ((buttonEnabled || hoverAlways) && enabled) {
if (propertyButton.hovered)
return hoveredBgColor // return here
else
return defaultBgColor // return here
} else {
return selectedBgColor // return here
}
if (propertyButton.pressed) // this condition is unreachable
return selectedBgColor // return here
}
}
}
添加上述
return
语句后,警告得到解决,但是if(propertyButton.pressed)
语句变得不可访问。我想知道避免这种无法达到的条件的最佳实践是什么。由于使用return使控件离开代码块,因此最佳实践是确保首先处理所有特殊情况
在您的情况下,将最后一次检查上移到该块的顶部,例如:
ButtonStyle {
padding.top: 0
padding.bottom: 0
padding.right: 0
padding.left: 0
background: Rectangle {
implicitHeight: enableButton.height
implicitWidth: enableButton.width
color: {
if (propertyButton.pressed) // moved up from below if-else block
return selectedBgColor //
if ((buttonEnabled || hoverAlways) && enabled) {
if (propertyButton.hovered)
return hoveredBgColor
else
return defaultBgColor
} else {
return selectedBgColor
}
}
}
}
如果总是希望在propertyButton.pressed为true的情况下选择颜色bgColor,请将其置于block@Ian我想你的建议解决了我的问题。我会加上它作为答案then@Ian谢谢接受并投票!