jupyter-widgets / ipydatagrid

Fast Datagrid widget for the Jupyter Notebook and JupyterLab
BSD 3-Clause "New" or "Revised" License
579 stars 51 forks source link

Selection changed #335

Closed Mark-Caple closed 2 years ago

Mark-Caple commented 2 years ago

I have looked around but cannot find a way of creating a handler for when a cell, row or column selection changes. Is this possible?

Basically I want to do something on one of these events. So if a new row is selected I want to be able to do something.

ibdafna commented 2 years ago

Hello @Mark-Caple 🙋‍♂️and welcome to the ipydatagrid community!

This is possible, yes. See code snippet below:

import ipydatagrid
import pandas as pd
import numpy as np
import ipywidgets as widgets

grid = ipydatagrid.DataGrid(pd.DataFrame([1,2,3,4]), selection_mode="row", layout={"height":"140px"})

def callback(e):
    print(e)

grid.observe(callback, names='selections')
grid

I will look into revamping the examples folder so it's highlighted there.

Mark-Caple commented 2 years ago

Unfortunately @ibdafna this does not work with Jupyter Notebook. I simply copy and pasted into a cell, executed the cell and the DataGrid appears but clicking on a row does not print anything.

Screenshot from 2022-08-18 15-02-44

Screenshot from 2022-08-18 15-03-30

ibdafna commented 2 years ago

@Mark-Caple it's just how ipywidgets work. You'll need an output widget to capture the stdout output generated by the code. This is done for you in JupyterLab (where I tested this)

import ipydatagrid
import pandas as pd
import numpy as np
import ipywidgets as widgets
from IPython.display import display

out = widgets.Output()
grid = ipydatagrid.DataGrid(pd.DataFrame([1,2,3,4]), selection_mode="row", layout={"height":"140px"})
display(out)
@out.capture()
def callback(e):
    print(e)

grid.observe(callback, names='selections')
grid
Mark-Caple commented 2 years ago

Perfect @ibdafna . Sometimes difficult to see the woods from the trees. Has been a long time since I've worked with notebooks but a 3rd party tool requires that I do so :+1:

ibdafna commented 2 years ago

@Mark-Caple this is valid feedback, thank you! I think us maintainers often tend to forget just how complex the widget system has become, and so it's tough for users to keep up with the changes. The solution is more elaborate documentation with examples that span beyond the bounds of the specific widget package. We are in the process of rewriting the documentation and I will definitely keep this in mind.