功能
使文字随着窗口的改变,始终保持在窗口中央。
程序
import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.3
Rectangle {
id:win; //设置窗口的id值,方便在别处引用
width: 300; //设置宽度和和高度
height: 200;
color:"red"; //设置窗口的背景色为红色
Text //定义一个文本对象
{
anchors.centerIn:parent;
id:txt; //设置文本的id
text:"center Text"; //设置文本的内容
font.pointSize: 20; //设置字体的大小
}
//信号处理的方式一
onWidthChanged: widthChanged(); //窗口宽度变化处理的信号槽
//信号处理的方式二
onHeightChanged: //窗口高度变化的信号槽
{
txt.y=(win.height-txt.height)/2; //文本纵向居中
//txt.anchors.verticalCenter=(win.anchors.verticalCenter-txt.anchors.verticalCenter)/2;//方式2
}
//定义一个方法
function widthChanged()
{
txt.x=(win.width-txt.width)/2; //文本横向居中
//txt.anchors.horizontalCenter=(win.anchors.horizontalCenter-txt.anchors.horizontalCenter)/2;//方式2
}
}
运行结果
说明
窗口变化,会触发两个信号,onWidthChanged(宽度改变)和onHeightChanged(高度改变),这两个信号触发时,分别使文本位于宽度中心和高度中心即可。
使文本位于宽度中心和高度中心,有以下几种方式:
1.宽度变化和高度变化时,均执行 txt.anchors.centerIn=parent;
2.宽度变化时,执行 txt.x=(win.width-txt.width)/2;,高度变化时,执行 txt.y=(win.height-txt.height)/2;
3.宽度变化时,执行 txt.anchors.horizontalCenter=(win.anchors.horizontalCenter-txt.anchors.horizontalCenter)/2; 高度变化时,执行 txt.anchors.verticalCenter=(win.anchors.verticalCenter-txt.anchors.verticalCenter)/2;。
或者,一种更简单的方式:
直接使用
onWindowChanged:{
txt.anchors.centerIn=parent;
}