我正在使用 QML 开发一个小型应用程序,我需要在文本组件上添加一个小阴影,以使其更具可读性,但是当我将 DropShadow 添加到列中的标签时,它会抛出错误:
“QML Column:无法为 Column 内的项目指定顶部、底部、verticalCenter、fill 或 centerIn anchor 。Column 将不起作用。”
但是文本应该相互重叠,这是我的示例代码:
import QtQuick 2.2
import QtGraphicalEffects 1.0
Item {
width: 100
height: 200
Column {
Label {
id: label1
anchors.horizontalCenter: parent.horizontalCenter
text: "First label"
}
DropShadow {
anchors.fill: label1
radius: 16
samples: 32
color: "#b0000000"
source: label1
}
Label {
id: label2
anchors.horizontalCenter: parent.horizontalCenter
text: "Second label"
}
DropShadow {
anchors.fill: label2
radius: 16
samples: 32
color: "#b0000000"
source: label2
}
}
}
我是不是犯了一些错误?或者我不能在列中使用 DropShadow 吗? 我应该使用 Item 而不是 Column 吗? 预先感谢您!
最佳答案
您遇到了几个问题。
您收到的错误消息已经解释了第一个问题;您不能在列中使用垂直 anchor ,并且 anchors.fill:parent
意味着水平和垂直 anchor 。您可以改用 width
和 height
属性:
import QtQuick 2.2
import QtGraphicalEffects 1.0
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
Window {
width: 100
height: 200
visible: true
Column {
Label {
id: label1
anchors.horizontalCenter: parent.horizontalCenter
text: "First label"
}
DropShadow {
width: label1.width
height: label1.height
radius: 16
samples: 32
color: "#b0000000"
source: label1
}
Label {
id: label2
anchors.horizontalCenter: parent.horizontalCenter
text: "Second label"
}
DropShadow {
width: label2.width
height: label2.height
radius: 16
samples: 32
color: "#b0000000"
source: label2
}
}
}
但是,这引入了新问题:
您可以看到标签有重复。 DropShadow
的文档对此进行了解释:
Generates a colorized and blurred shadow image of the source and places it behind the original, giving the impression that source item is raised from the background.
因此,您可以在 label1
和 label2
上设置 visible: false
。
下一个问题是 DropShadow
将被限制在 Label
的边界矩形内。对于 DropShadow
文档中的示例,这不是问题,因为内容的边界比实际项目的边界小得多:
由于构成文本的像素与标签
的边界之间的距离并不大,因此您必须自己考虑这一点。
我怀疑这是最优雅的解决方案,但我不知道更好的解决方案:
import QtQuick 2.4
import QtQuick.Window 2.0
import QtQuick.Controls 1.0
import QtGraphicalEffects 1.0
Window {
id: win
width: 150
height: 150
visible: true
Item {
width: 100
height: 200
Column {
Item {
width: label1.implicitWidth + 20
height: label1.implicitHeight + 20
anchors.horizontalCenter: parent.horizontalCenter
visible: false
Label {
id: label1
text: "First label"
anchors.centerIn: parent
}
}
DropShadow {
width: label1.width
height: label1.height
radius: 4
samples: 8
color: "#b0000000"
source: label1
}
Item {
width: label2.implicitWidth + 20
height: label2.implicitHeight + 20
anchors.horizontalCenter: parent.horizontalCenter
visible: false
Label {
id: label2
text: "Second label"
anchors.centerIn: parent
}
}
DropShadow {
width: label2.width
height: label2.height
radius: 4
samples: 8
color: "#b0000000"
source: label2
}
}
}
}
请注意,我还减小了阴影的半径以使其更加明显。
关于qt - 无法在 Column 中使用 DropShadow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520772/