widgetti / ipyaggrid

Using ag-Grid in Jupyter notebooks.
MIT License
56 stars 14 forks source link

Programmatically auto size the columns after creation? #37

Open gioxc88 opened 1 year ago

gioxc88 commented 1 year ago

Is there a way in python to programmatically auto size the columns after the grid has been created (for example after updating the data)?

thanks

mariobuikhuizen commented 1 year ago

It's not from python, but this does resize after edit:

from ipyaggrid import Grid

grid = Grid(
    columns_fit="auto",
    grid_data=[
        {"make": "Toyota", "model": "Celica", "price": 35000},
        {"make": "Ford", "model": "Mondeo", "price": 32000},
        {"make": "Porsche", "model": "Boxster", "price": 72000},
    ],
    grid_options={
        "defaultColDef": {
            'valueSetter': '''__js__: function(params) {
                 params.data[params.colDef.field] = params.newValue;
                 const { columnApi } = params.column.gridOptionsWrapper.gridOptions;
                 columnApi.autoSizeColumns(columnApi.getColumns().map(col => col.colId));
            }'''
        },
        'columnDefs': [
            {"headerName": "Make", "field": "make", "editable": True},
            {"headerName": "Model", "field": "model", "editable": True},
            {"headerName": "Price", "field": "price", "editable": True, 'type': 'numericColumn'}
        ]
    },
)

grid

Does this work for your use case?

afbarbaro commented 11 months ago

I've done this within the IPython environment inside Jupyterlab using the following code:

from IPython.core.display import Javascript
from IPython.display import display

def resize_columns(self):
    display(Javascript(f"grid.gridOptions.columnApi.autoSizeAllColumns()"))

If you're calling this inside a callback (in my case I'm calling this inside a button callback that first loads data into the grid and then resizes the columns, you'll have to make sure that you have an active output stream present/captured, otherwise the Javascript display won't do anything:

@self._out.capture()
def on_click(widget: v.Btn, event, data):
    try:
        # Hide the run button and show the progress circle
        widget.hide()
        progress.show()

        # Update Grid
        self.grid.update_data(fetch_data(session, date_picker.dates))
        self.grid.resize_columns()

    finally:
        widget.show()
        progress.hide()