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
- Fixed ScrollBar Dimensions: By setting
height: 780explicitly, you override any automatic resizing from the ListView container, ensuring the ScrollBar stays at your image's original height. - Preserve Image Size: The Image's
widthandheightare set to itsnaturalSize(the original dimensions of the image file), andfillMode: Image.PreserveAspectFitensures it doesn't stretch or squish to fit the ScrollBar. - Output Height Data: Using
sb.onLoaded, we wait for the image to fully load before accessing itsnaturalSize.heightand 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
相关产品推荐
相关产品推荐

