QML自定义ComboBox样式问题:悬停元素高度与选中矩形异常
Hey Steve, let's work through these two snags with your custom ComboBox. I've run into similar quirks before, so here's how to sort them out:
1. Fixing Height Mismatch Between rectDlgt and itemDlgt
The root issue here is that your rectDlgt isn't inheriting or binding to the height of itemDlgt. When you see itemDlgt report 40 but rectDlgt only 16, it means rectDlgt is using its default implicit height instead of matching its parent's intended size.
To fix this, explicitly bind rectDlgt's dimensions to its parent (which should be itemDlgt). Here's how you'd adjust your delegate code:
Component { id: itemDlgt Item { width: parent.width height: 40 // Your intended item height Rectangle { id: rectDlgt anchors.fill: parent // This forces it to match parent's width AND height color: hovered ? "#eee" : "transparent" // If you prefer explicit bindings over anchors: // width: parent.width // height: parent.height } // Rest of your item content (text, icons, etc.) Text { anchors.centerIn: parent text: model.display } } }
If rectDlgt isn't a direct child of itemDlgt, make sure you're binding to the correct parent or explicitly setting height: itemDlgt.height instead. Also double-check that itemDlgt's height is actually set to 40 (sometimes implicit heights can override explicit values if you're not careful with layout hierarchy).
2. Removing/Styling the Gray Rectangle on Item Click
That gray rectangle is the default ListView Highlight component. By default, ListView uses a plain gray rectangle to indicate the selected item, even if you've customized your delegate. You can either disable it entirely or replace it with a style that matches your hover state.
Option 1: Disable the Highlight Completely
Add this to your ListView definition:
ListView { // ... your existing ListView properties highlight: Rectangle { color: "transparent" } }
Option 2: Match Highlight to Hover Style
If you want the selected item to have the same visual as your hover state, create a custom highlight that mirrors rectDlgt:
ListView { // ... your existing ListView properties highlight: Rectangle { color: "#eee" // Same as your hover color radius: 2 // Match any radius you have on rectDlgt } highlightFollowsCurrentItem: true // Ensure it tracks the selected item }
Also, if you're handling selection manually with currentItem, double-check that you're not accidentally triggering any default styling that overrides your custom delegate.
Give these changes a try—they should resolve both issues you're seeing!
内容的提问来源于stack exchange,提问作者SteveTJS

