在Qt Quick中将SVG图像的画布大小缩小到实际绘制大小

4

大家好!

我正在开发一个Qt Quick Controls 2应用程序,需要缩小一个SVG图像,使其适合屏幕高度,并将其作为ColumnLayout的一部分。以下是我的代码:

Page {
    title: "About"

    ColumnLayout {
        anchors.fill: parent
        spacing: 20

        Image {
            id: app_logo
            source: "images/app_logo.svg"
            mipmap: true
            Layout.maximumWidth: Math.min(parent.width, 300)
            Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
            verticalAlignment: Qt.AlignTop
            fillMode: Image.PreserveAspectFit
        }

        Label {
            text: "Version 0.1"
            font.pointSize: 15
            Layout.fillWidth: true
            horizontalAlignment: Qt.AlignHCenter
        }
    }
}

原始SVG大小为1200x500,生成的绘制图像大小为300x125,也通过paintWidth和paintHeight属性显示。我面临的问题是SVG的画布没有改变,仍然是1200x500,导致其他控件(例如标签)移出屏幕:

应用程序截图

如何将画布大小设置为实际绘制大小而不会引起绑定循环?

2个回答

3

在Qt Quick中使用SVG图像时,请将它们的sourceSize修改为与项目大小相匹配:

Image {
        id: app_logo
        source: "images/app_logo.svg"
        mipmap: true
        Layout.maximumWidth: Math.min(parent.width, 300)
        Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
        verticalAlignment: Qt.AlignTop
        sourceSize: Qt.size(width, height) //important
    }

突出显示的这一行更改了画布(渲染)大小。


0
根据paintedHeight文档

当使用Image.PreserveAspectFitImage.PreserveAspectCrop时,paintedWidth或paintedHeight可以比Image项的宽度和高度小或大。

由于设置了fillMode: Image.PreserveAspectFit,因此paintedHeight为125。但是,图像的height未设置,并且默认情况下保持为500像素。为了分配正确的高度而不会导致绑定循环,您可以设置Layout.preferredHeight属性并自行计算PreserveAspectFit
Image {
    id: app_logo
    source: "images/app_logo.svg"
    mipmap: true
    Layout.maximumWidth: Math.min(parent.width, 300)
    Layout.alignment: Qt.AlignHCenter | Qt.AlignTop
    verticalAlignment: Qt.AlignTop

    //PreserveAspectFit 
    Layout.preferredHeight: (width / sourceSize.width) * sourceSize.height
}

谢谢,这段代码可用;但是仍有一个警告:qrc:/main.qml:20:5: QML Page: Binding loop detected for property "contentHeight" - Ilya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接