我试图使用sourceClipRect属性在QML中只显示图像的正确部分
下面是代码的一个片段
Image
{
id : _image
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
fillMode: Image.PreserveAspectCrop
width: parent.width
height: parent.height
sourceSize.width : undefined
sourceSize.height : undefined
source : imagePath
sourceClipRect: Qt.rect(sourceSize.width/2, 0, sourceSize.width/2, sourceSize.height)
smooth : true
mipmap : true
}
此图像位于具有固定宽度和高度的项内。
这给了我一个警告和一个属性sourceClipRect的绑定循环,我猜是因为在sourceClipRect中使用了sourceSize
我不能在sourceClipRect中使用硬数字,因为我不知道图片的原始大小
你知道怎样才能避免这个绑定循环吗?也许通过另一种方法获得原始的宽度和高度,但我不知道在纯QML中除了sourceSize以外的任何其他方法
Ps :结果和预期的一样工作,并且运行良好,我只是有一个丑陋的警告声明绑定循环。
提前谢谢
发布于 2022-05-10 09:53:44
我终于找到了一个可以接受的解决办法。这可能不是最干净的,但我可以接受。
但是在图像的实例化中,我只是保存var而没有绑定,如下所示
Image
{
id : _image
property var sourceSizeWidth :{sourceSizeWidth = sourceSize.width} //initializing this way avoids the binding between sourceSize.Width and sourceSizeWidth
property var sourceSizeHeight :{sourceSizeHeight = sourceSize.height} //initializing this way avoids the binding between sourceSize.height and sourceSizeHeight
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
fillMode: Image.PreserveAspectCrop
width: parent.width
height: parent.height
sourceSize.width : undefined
sourceSize.height : undefined
source : imagePath
sourceClipRect: Qt.rect(sourceSizeWidth/2, 0, sourceSizeWidth/2, sourceSizeHeight) //Use the unbinded var to set the sourceClipRect
smooth : true
mipmap : true
}
这样的初始化避免了新创建的sourceSizeWidth和QML属性sourceSize.width之间的绑定。
property var sourceSizeWidth :{sourceSizeWidth = sourceSize.width}
正如我所说的,这并不是最干净的,而且可能有一种更聪明的方法,但是现在它已经足够了,它工作得很好,而且没有警告绑定循环。
干杯!
https://stackoverflow.com/questions/72114804
复制相似问题