main.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python3
  2. from nicegui import ui
  3. fields = [
  4. {'name': 'name', 'label': 'Name', 'field': 'name', 'required': True},
  5. {'name': 'age', 'label': 'Age', 'field': 'age', 'sortable': True},
  6. ]
  7. rows = [
  8. {'id': 0, 'name': 'Alice', 'age': 18},
  9. {'id': 1, 'name': 'Bob', 'age': 21},
  10. {'id': 2, 'name': 'Lionel', 'age': 19},
  11. {'id': 3, 'name': 'Michael', 'age': 32},
  12. {'id': 4, 'name': 'Julie', 'age': 12},
  13. {'id': 5, 'name': 'Livia', 'age': 25},
  14. {'id': 6, 'name': 'Carol'},
  15. ]
  16. def add_row(item):
  17. rows.append(item)
  18. table.update()
  19. def remove_row(keys):
  20. for i in range(len(rows)):
  21. if rows[i]['id'] in keys:
  22. del rows[i]
  23. table.update()
  24. with ui.qtable(title='QTable', columns=fields, rows=rows, key='id', selection='single') as table:
  25. with table.add_slot('top-right'):
  26. with ui.input(placeholder='Search').props('type="search"').bind_value(table, 'filter') as search:
  27. with search.add_slot('append'):
  28. ui.icon('search')
  29. with table.add_slot('top-row'):
  30. with table.row():
  31. with table.cell().props('colspan="100%"'):
  32. ui.label('This is a top row').classes('text-center')
  33. with table.add_slot('bottom-row'):
  34. with table.row():
  35. with table.cell().props('colspan="2"'):
  36. new_name = ui.input()
  37. with table.cell():
  38. ui.button('add row', on_click=lambda: add_row({'id': len(rows), 'name': new_name.value, 'age': 10}))
  39. ui.label('').bind_text_from(table, 'selected', lambda val: f'Current selection: {val.__repr__()}')
  40. ui.button('Remove selection', on_click=lambda: remove_row(table.selected['keys'])).bind_visibility(table, 'selected')
  41. ui.run()