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

如何为Godot的VBox控件节点添加可收缩的左侧可选内边距?

实现可收缩的VBox左侧内边距

Margin Container的边距是固定属性,无法随容器空间变化自动收缩,你可以用以下两种方案解决需求:

方案一:HBox + 可收缩占位节点

这是最简洁的实现方式,通过外层HBox配合占位节点模拟可收缩内边距:

  1. 用HBox作为外层容器,替代Margin Container
  2. 在HBox左侧添加一个Region(或Spacer)作为占位元素,用来模拟内边距
  3. 给占位元素设置最小宽度为0、首选宽度为你需要的默认内边距值,同时开启HBox.hgrow="ALWAYS"让它在空间不足时自动收缩

以JavaFX为例,代码示例如下:

HBox outerBox = new HBox();
// 左侧可收缩占位节点
Region leftSpacer = new Region();
leftSpacer.setMinWidth(0);
leftSpacer.setPrefWidth(20); // 默认内边距20px
HBox.setHgrow(leftSpacer, Priority.ALWAYS);

VBox contentBox = new VBox();
// 向contentBox添加你的内容组件

outerBox.getChildren().addAll(leftSpacer, contentBox);

如果用FXML编写:

<HBox>
    <Region minWidth="0" prefWidth="20" HBox.hgrow="ALWAYS"/>
    <VBox>
        <!-- 放置VBox的内容组件 -->
    </VBox>
</HBox>

方案二:自定义VBox重写布局逻辑

如果需要更定制化的行为,可以自定义VBox类,通过重写布局方法动态调整内边距:

public class ResizablePaddingVBox extends VBox {
    private double preferredLeftPadding = 20;

    @Override
    protected void layoutChildren() {
        double availableWidth = getWidth() - getInsets().getLeft() - getInsets().getRight();
        // 计算内容所需的最小宽度(简化版,实际需考虑VBox的间距等)
        double contentMinWidth = getChildren().stream()
                .mapToDouble(node -> node.minWidth(-1))
                .max().orElse(0);

        // 动态计算当前左侧内边距:不超过首选值,且保证内容能完整显示
        double currentLeftPadding = Math.max(0, Math.min(preferredLeftPadding, availableWidth - contentMinWidth));
        setPadding(new Insets(getPadding().getTop(), getPadding().getRight(), getPadding().getBottom(), currentLeftPadding));

        super.layoutChildren();
    }

    public void setPreferredLeftPadding(double padding) {
        this.preferredLeftPadding = padding;
        requestLayout();
    }
}

使用这个自定义VBox时,当容器宽度充足,左侧保持你设置的首选内边距;空间不足时,内边距会自动收缩至0,确保内容不会被挤压。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:12:05