防止SWT ScrolledComposite吃掉部分孩子

时间:2020-03-05 18:45:11  来源:igfitidea点击:

我做错什么了?

这是我的代码的摘录:

public void createPartControl(Composite parent) {
  parent.setLayout(new FillLayout());
  ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
  scrollBox.setExpandHorizontal(true);
  mParent = new Composite(scrollBox, SWT.NONE);
  scrollBox.setContent(mParent);
  FormLayout layout = new FormLayout();
  mParent.setLayout(layout);
  // Adds a bunch of controls here
  mParent.layout();
  mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
}

...但是它剪辑了最后一个按钮:

bigbrother82:那没用。

SCdF:我尝试了建议,现在滚动条不见了。我需要做更多的工作。

解决方案

回答

布局后,我们是否不需要重新计算scrollBox的大小?

回答

如果我没记错的话,我们需要交换

mParent.layout();

mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));

这样我们就可以:

public void createPartControl(Composite parent) {
  parent.setLayout(new FillLayout());
  ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
  scrollBox.setExpandHorizontal(true);
  mParent = new Composite(scrollBox, SWT.NONE);
  scrollBox.setContent(mParent);
  FormLayout layout = new FormLayout();
  mParent.setLayout(layout);
  // Adds a bunch of controls here
  mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
  mParent.layout();
}

回答

布局完成后,尝试在ScrolledComposite上设置.setMinWidth和.setMinHeight,并传递其主要组合的大小。

回答

当使用ScrolledComposite时,这是一个常见的障碍。当它太小以至于必须显示滚动条时,客户端控件必须水平缩小以为滚动条腾出空间。这具有使某些标签换行的副作用,这使以下控件进一步向下移动,从而增加了内容合成所需的最小高度。

我们需要监听内容组合(mParent)上的宽度变化,在给定新的内容宽度的情况下再次计算最小高度,并在具有新高度的滚动组合上调用setMinHeight()

public void createPartControl(Composite parent) {
  parent.setLayout(new FillLayout());
  ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
  scrollBox.setExpandHorizontal(true);
  scrollBox.setExpandVertical(true);

  // Using 0 here ensures the horizontal scroll bar will never appear.  If
  // you want the horizontal bar to appear at some threshold (say 100
  // pixels) then send that value instead.
  scrollBox.setMinWidth(0);

  mParent = new Composite(scrollBox, SWT.NONE);

  FormLayout layout = new FormLayout();
  mParent.setLayout(layout);

  // Adds a bunch of controls here

  mParent.addListener(SWT.Resize, new Listener() {
    int width = -1;
    public void handleEvent(Event e) {
      int newWidth = mParent.getSize().x;
      if (newWidth != width) {
        scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y);
        width = newWidth;
      }
    }
  }

  // Wait until here to set content pane.  This way the resize listener will
  // fire when the scrolled composite first resizes mParent, which in turn
  // computes the minimum height and calls setMinHeight()
  scrollBox.setContent(mParent);
}

在侦听大小更改时,请注意,我们忽略了宽度保持不变的任何大小调整事件。这是因为只要宽度相同,内容高度的变化就不会影响内容的最小高度。