How do I autosize the column in SlickGrid?

2019-01-16 16:16发布

I want slickgrid to autosize the columns based on the widest content or header text - whichever is wider. In simpler terms, I want it to simulate the default behavior of regular HTML tables when it comes to column sizing. How can I do it in slickgrid?

7条回答
SAY GOODBYE
2楼-- · 2019-01-16 16:22

When constructing your options, you can use forceFitColumns: true

var options = {
    enableCellNavigation: true,
    forceFitColumns: true
};

This will make the columns fill the entire width of your grid div.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-16 16:28

The OP is looking for columns to grow to match their content. grid.autosizeColumns() grows the cells to fit the parent container, which is not the same thing.

I have added this feature, and it is about as manual as you might imagine. You loop through the displayed cells and measure each one, saving the widest cell and using that width to set the width of your column. SlickGrid gives you good access to the cells in the viewport, so that works nicely.

The measurement algorithm is your big decision. You may put the content off screen and measure it, as @jay suggests. This works, but it is the slowest method, as it requires a repaint to insert, and a repaint when you remove. There may be ways to optimize. The solution I went with is to measure the width of every letter in the alphabet, as well as other typographic characters we come across, and sum them to generate a width. Yes, this sounds absurd. It has many constraints: The font size must be the same, it doesn't support images, there can't be any line returns, and more. If you can live with the constraints though, you can calculate sizes for a huge grid viewport in <5ms, because the character widths are only measured once.

After you get the sizes of the columns, you assign them to your columns using grid.setColumns().

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-16 16:28

You should be able to call the autosizeColumns() method of the grid object.

grid.autosizeColumns();
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-01-16 16:28

Make this simple adjustment to Naresh's https://github.com/naresh-n/slickgrid-column-data-autosize, on the init function:

  • Add $container.ready(resizeAllColumns); to the init function.

This ensures the columns autoresize on initial load

查看更多
Emotional °昔
6楼-- · 2019-01-16 16:30

Insert the text into an off-screen element and retrieve the width of the element. This is what excanvas does to measure text. Use this to set the width of the column since it's expecting a pixel value.

查看更多
Animai°情兽
7楼-- · 2019-01-16 16:37

I added this after the grid is drawn and it works fine.

$(window).resize(function() {
var cols = grid.getColumns();
grid.setColumns(cols);
})
查看更多
登录 后发表回答