这是我的QML文件,其中包含Text组件:
import QtQuick 2.0
Item {
id: idItmWrapText
Text {
id: idTxtTitle
text: qsTr("Hello World")
font.pointSize: 20
}
}
Run Code Online (Sandbox Code Playgroud)
现在在Test.qml文件中我将实例化上面的组件三次,但它只在输出中显示一次.我的Test.qml文件如下所示:
import QtQuick 2.0
Item {
id: idItmWrapRect
width: 400
height: 400
Rectangle{
id: idRectDisplay
width: parent.width
height: parent.height
Column {
id: idClmnLayout
spacing: 50
x: 195
y: 200
MyText{
}
MyText{
}
MyText{
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
**Hello World** //showing only once
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
这是完全正常的:实际上你的组件显示3次但彼此重叠,所以你认为只有其中一个......
为什么?
只是因为在你的组件中,你将Text放在一个Item中,但你没有告诉Item与内部Text的大小相同,所以它保持0x0大小.
但为什么文字可见?
默认情况下,项目不会被剪裁,这意味着即使内容超出了项目的边框,也可以显示内容.
怎么解决?
只需将Text正确锚定在Item内,并将Item高度绑定在自定义组件内的Text实际高度:
import QtQuick 2.0
Item {
id: itmWrapText;
width: 400; // default width of the component
height: txtTitle.contentHeight; // bind height on Text content size
property alias title : txtTitle.text; // btw, expose property to be able to set text
Text {
id: txtTitle;
text: qsTr ("Hello World");
font.pointSize: 20;
wrapMode: Text.WrapAtWordBoundaryOrAnywhere; // wrap content if necessary
anchors { // force Text to stay in parent Item
top: parent.top;
left: parent.left;
right: parent.right;
}
}
}
Run Code Online (Sandbox Code Playgroud)
它已经完成了!
| 归档时间: |
|
| 查看次数: |
312 次 |
| 最近记录: |