PDA

View Full Version : Autosize Grid Columns to Fit Contents & Header Text



bartonjd
26 Jul 2011, 6:54 AM
This is just a simple plugin that ensures that all grid columns are wide enough for their header text and their contents.



Ext.ns('Ext.plugins');
Ext.plugins.GridAutoWidths = function(config) {
Ext.apply(this, config);
};

Ext.extend(Ext.plugins.GridAutoWidths, Ext.util.Observable, {
init: function (cmp) {
cmp.store.on('load', function(g){
var numCol = cmp.getColumnModel().getColumnCount();
for(var i=0;i<numCol;i++){
var header = cmp.colModel.getColumnHeader(i);
var id = cmp.getView().mainHd.dom.getElementsByTagName('a')[i];
var width = Ext.util.TextMetrics.createInstance(Ext.get(id)).getWidth(header) + 10;
cmp.getColumnModel().setColumnWidth(i,width);
var data = Ext.get(cmp.getView().getRow(0).getElementsByTagName('div')[i]).dom.textContent;
dataWidth = Ext.util.TextMetrics.createInstance(Ext.get(cmp.getView().getRow(0).getElementsByTagName('div')[i])).getWidth(data)+10;
if (width < dataWidth){
cmp.getColumnModel().setColumnWidth(i,dataWidth)
}
}
});
}
});

romankuzmik
20 Nov 2013, 11:28 AM
this is what I have for Ext 4.2:


Ext.define('CUI.ux.plugin.GridAutoWidths', {
extend: 'Ext.AbstractPlugin',


init: function (grid) {
grid.store.on('load', function(){
var columnsManager = grid.getView().getHeaderCt();
var columnsCount = columnsManager.getColumnCount();
for (var headerIndex=0; headerIndex<columnsCount; headerIndex++){
var column = columnsManager.getHeaderAtIndex(headerIndex);
columnsManager.autoSizeColumn(column);
column.setSize(column.getSize().width + 5, column.getSize().height);
}
});
}
});