QML Row组件不可见项布局异常,求最优解决方案
Hey there! Let's break down how to solve your problem: you want columns in a Row to keep their position even if all buttons inside are hidden, while also making visible buttons in the column shift up automatically when others are hidden.
Key Issues to Address
- When you set
visible: falseon a Column in a Row, Qt Quick removes it from the layout entirely (no placeholder space left). - Using
opacity: 0keeps the space, but leaves empty gaps where hidden buttons would be instead of shifting visible buttons up.
Optimal Implementation
Here's a revised version of your code that meets both requirements:
Rectangle{ width: parent.width height: parent.height Component{ id: itemDelegate Item { id: itemId width: listView.width; height: listView.height * 0.20 Row{ spacing: listView.height * 0.05 // Adjust spacing as needed Repeater{ model:5 // Placeholder Item to ensure the column keeps its position in the Row Item { // Fixed width to reserve space in the Row width: listView.width / 5 // Divide by number of columns for equal spacing // Auto-height based on visible buttons, with a minimum height for empty columns height: columnContent.implicitHeight > 0 ? columnContent.implicitHeight : listView.height * 0.15 Column { id: columnContent anchors.top: parent.top anchors.horizontalCenter: parent.horizontalCenter spacing: 4 Button{ text: index visible: (index % 2) === 0 // Hide button entirely without taking space when not visible height: visible ? implicitHeight : 0 width: parent.width * 0.8 // Adjust button width as needed } Button{ text: index visible: (index % 3) === 0 height: visible ? implicitHeight : 0 width: parent.width * 0.8 } } } } } } } ListView{ id:listView anchors.fill: parent anchors.margins: parent.width * 0.08 delegate: itemDelegate model: aaModel // Ensure your model is defined elsewhere clip:true } }
How It Works
- Placeholder Item for Columns: We wrap each Column in an
Itemthat has a fixedwidthand dynamicheight. This ensures the Row always reserves space for the column, even if all buttons inside are hidden. - Dynamic Button Height: For each Button, we set
height: visible ? implicitHeight : 0. When the button is hidden, it takes no vertical space, so visible buttons in the Column automatically shift up. - Minimum Height for Empty Columns: The placeholder Item uses
height: columnContent.implicitHeight > 0 ? columnContent.implicitHeight : listView.height * 0.15to maintain a small minimum height when no buttons are visible, keeping the column's position in the Row.
Additional Tips
- Adjust the
widthof the placeholder Item to match your desired column spacing (usinglistView.width / 5ensures equal width for 5 columns). - Tweak the
spacingvalues in Row and Column to get the exact layout you want. - If you need more control over layout alignment, consider using
ColumnLayoutinside the placeholder Item (just make sure to setLayout.fillWidth: truefor buttons).
内容的提问来源于stack exchange,提问作者J_makwie
相关产品推荐
相关产品推荐

