Combo in columnheader with swt

2019-01-20 14:33发布

问题:

I want a table that has a combo as one of its columnheaders. I already found out that it is impossible with Table from this question: Controls (Combo, Radio, Text) in column header SWT

Is there a way around that? I tried TableViewer but didn't find a way to do it with it either. Is there any way this can be achieved?

回答1:

You could create your own column headers in a Composite above the table using normal controls.

You will then need to adjust the size of these controls to match the table column sizes. One way to do this is to use a table layout class extending the jface TableColumnLayout and overriding the setColumnWidths method which is called each time the column sizes change, so you can adjust your header control widths.

Note: TableColumnLayout needs to be on a Composite containing just the Table rather than directly on the Table.

So something like this for the layout:

/**
 * Table column layout extended to manage a separate table header.
 */
public class TableColumnLayoutWithSeparateHeader extends TableColumnLayout
{
  /** Header composite */
  private final Composite _headerComposite;
  /** Right margin adjust */
  private final int _rightMargin;


  /**
   * Constructor.
   *
   * @param headerComposite Header composite
   * @param rightMargin Right margin value
   */
  public TableColumnLayoutWithSeparateHeader(final Composite headerComposite, final int rightMargin)
  {
    super();

    _headerComposite = headerComposite;
    _rightMargin = rightMargin;
  }


  /**
   * {@inheritDoc}
   * @see org.eclipse.jface.layout.TableColumnLayout#setColumnWidths(org.eclipse.swt.widgets.Scrollable, int[])
   */
  @Override
  protected void setColumnWidths(final Scrollable tableTree, final int [] widths)
  {
    super.setColumnWidths(tableTree, widths);

    // Update the header composite

    final Control [] children = _headerComposite.getChildren();

    final int size = Math.min(widths.length, children.length);

    for (int index = 0; index < size; ++index) {
       final GridData data = (GridData)children[index].getLayoutData();

       int width = widths[index];
       if (index == (size - 1))
         width -= _rightMargin;

       data.widthHint = width; 
     }

    _headerComposite.layout();
  }
}