我想通过修改元素的高度
来显示/隐藏元素。这是显示我的问题的示例代码:
import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4
Window {
id: win
width: 300
height: 300
visible: true
ColumnLayout {
width: parent ? parent.width : 200
Switch {
id: someswitch
Layout.alignment: Qt.AlignCenter
}
Label {
id: myText
text: "dummy"
height: 0
wrapMode: Text.WordWrap
clip: true
Layout.fillWidth: true
Layout.alignment: Qt.AlignCenter
states: State {
name: "visible"
when: someswitch.checked
PropertyChanges { target: myText; height: implicitHeight }
}
Behavior on height {
NumberAnimation { duration: 100 }
}
}
}
}
我还没有添加Transition
/Animation
,但是这个阶段的行为已经是错误的。 someswitch
默认未选中,但会显示文本。另一方面,检查开关后,文本隐藏并且再也不会出现。
我该如何处理?我希望文本“滑出”。我不想改变它的不透明度
。
最佳答案
一般来说,要保证State
的一致性,才能保证Transition
正常工作。可以通过以下方式实现一致性:
- 通过定义一个一致的默认状态
- 通过定义所有必要的
State
,就像提出的其他不错的答案一样。
首先要注意的是,Layout
的存在在这里起着关键作用。 Layout
在某种程度上取代了 Items
的height
设置及其minimumHeight
属性。在这种情况下,在 height
上定义的 State
不会真正影响 Label
。显而易见的解决方案是强制 State
的一致性,但超过 Layout.preferredHeight
,即定义默认的 State
以及 “不可见” "
为 Layout.preferredHeight
而不是 height
设置了不同的值。您的代码的重新访问版本可能如下所示:
Label {
id: myText
text: "dummy"
wrapMode: Text.WordWrap
clip: true
Layout.fillWidth: true
Layout.alignment: Qt.AlignCenter
Layout.preferredHeight: implicitHeight //visible --> layout height = text implicit height
states: State {
name: "invisible"
when: !someswitch.checked
PropertyChanges { target: myText; Layout.preferredHeight: 0 } // invisible --> layout item height forced to zero
}
Behavior on Layout.preferredHeight {
NumberAnimation { duration: 100 }
}
}
关于qt - 动画高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444756/