main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from nicegui import ui
  2. data = [
  3. {"id": 0, "name": "Alice", "age": 18},
  4. {"id": 1, "name": "Bob", "age": 21},
  5. {"id": 2, "name": "Carol", "age": 20},
  6. ]
  7. def update_data_from_table_change(e):
  8. ui.notify(f"Update with {e.args['data'] }")
  9. uprow = e.args["data"]
  10. data[:] = [row | uprow if row["id"] == uprow["id"] else row for row in data]
  11. table = ui.aggrid(
  12. {
  13. "columnDefs": [
  14. {"field": "name", "editable": True, "sortable": True},
  15. {"field": "age", "editable": True},
  16. {"field": "id"},
  17. ],
  18. "rowData": data,
  19. "rowSelection": "multiple",
  20. "stopEditingWhenCellsLoseFocus": True,
  21. }
  22. ).on("cellValueChanged", update_data_from_table_change)
  23. async def delete_selected():
  24. result = [row["id"] for row in await table.get_selected_rows()]
  25. ui.notify(f"delete rows {result}")
  26. data[:] = [row for row in data if row["id"] not in result]
  27. table.update()
  28. def new_row():
  29. newid = max(dx["id"] for dx in data) + 1
  30. ui.notify(f"new row with id {newid}")
  31. data.append({"id": newid, "name": "New name", "age": None})
  32. table.update()
  33. ui.button("Delete selected", on_click=delete_selected)
  34. ui.button("New row", on_click=new_row)
  35. ui.label().classes("whitespace-pre font-mono").bind_text_from(
  36. globals(), "data", lambda x: "Data: \n{0}".format("\n".join([str(y) for y in x]))
  37. )
  38. ui.run()