You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QML中如何固定ListView自定义滚动条高度并输出高度数据

Solution to Keep ScrollBar Image at Original Height and Output Height Data

To fix your ScrollBar so it displays the original image without resizing and outputs the image's height, here's how to adjust your code:

Modified Code

ScrollBar {
    id: bar
    // Explicitly set initial dimensions to match your image's original size
    width: 33
    height: 780

    contentItem: Image {
        id: sb
        source: "1.png"
        
        // Prevent image scaling by using its natural dimensions
        fillMode: Image.PreserveAspectFit
        width: naturalSize.width
        height: naturalSize.height
        
        // Center the image within the ScrollBar (optional, adjust as needed)
        anchors.centerIn: parent
    }

    // Log the original image height once it's loaded
    Component.onCompleted: {
        sb.onLoaded.connect(() => {
            console.log("Original image height:", sb.naturalSize.height);
            // Optional: Dynamically set ScrollBar size from the image's natural dimensions
            // bar.height = sb.naturalSize.height;
            // bar.width = sb.naturalSize.width;
        });
    }

    // Link the ScrollBar to your ListView (replace 'listView' with your actual ListView id)
    target: listView
}

Key Changes Explained

  1. Fixed ScrollBar Dimensions: By setting height: 780 explicitly, you override any automatic resizing from the ListView container, ensuring the ScrollBar stays at your image's original height.
  2. Preserve Image Size: The Image's width and height are set to its naturalSize (the original dimensions of the image file), and fillMode: Image.PreserveAspectFit ensures it doesn't stretch or squish to fit the ScrollBar.
  3. Output Height Data: Using sb.onLoaded, we wait for the image to fully load before accessing its naturalSize.height and logging it to the console. This avoids getting incorrect values if the image hasn't loaded yet.

Optional Dynamic Adjustment

If you don't want to hardcode the image dimensions, you can comment out the fixed width and height on the ScrollBar and uncomment the lines inside the onLoaded handler. This will automatically set the ScrollBar's size to match the image's original dimensions, even if you change the image file later.

内容的提问来源于stack exchange,提问作者Ryou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:33:12