1
0

table_documentation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. from nicegui import ui
  2. from . import doc
  3. @doc.demo(ui.table)
  4. def main_demo() -> None:
  5. columns = [
  6. {'name': 'name', 'label': 'Name', 'field': 'name', 'required': True, 'align': 'left'},
  7. {'name': 'age', 'label': 'Age', 'field': 'age', 'sortable': True},
  8. ]
  9. rows = [
  10. {'name': 'Alice', 'age': 18},
  11. {'name': 'Bob', 'age': 21},
  12. {'name': 'Carol'},
  13. ]
  14. ui.table(columns=columns, rows=rows, row_key='name')
  15. @doc.demo('Omitting columns', '''
  16. If you omit the `columns` parameter, the table will automatically generate columns from the first row.
  17. Labels are uppercased and sorting is enabled.
  18. ''')
  19. def omitting_columns():
  20. ui.table(rows=[
  21. {'make': 'Toyota', 'model': 'Celica', 'price': 35000},
  22. {'make': 'Ford', 'model': 'Mondeo', 'price': 32000},
  23. {'make': 'Porsche', 'model': 'Boxster', 'price': 72000},
  24. ])
  25. @doc.demo('Default column parameters', '''
  26. You can define default column parameters that apply to all columns.
  27. In this example, all columns are left-aligned by default and have a blue uppercase header.
  28. ''')
  29. def default_column_parameters():
  30. ui.table(rows=[
  31. {'name': 'Alice', 'age': 18},
  32. {'name': 'Bob', 'age': 21},
  33. ], columns=[
  34. {'name': 'name', 'label': 'Name', 'field': 'name'},
  35. {'name': 'age', 'label': 'Age', 'field': 'age'},
  36. ], column_defaults={
  37. 'align': 'left',
  38. 'headerClasses': 'uppercase text-primary',
  39. })
  40. @doc.demo('Table with expandable rows', '''
  41. Scoped slots can be used to insert buttons that toggle the expand state of a table row.
  42. See the [Quasar documentation](https://quasar.dev/vue-components/table#expanding-rows) for more information.
  43. ''')
  44. def table_with_expandable_rows():
  45. columns = [
  46. {'name': 'name', 'label': 'Name', 'field': 'name'},
  47. {'name': 'age', 'label': 'Age', 'field': 'age'},
  48. ]
  49. rows = [
  50. {'name': 'Alice', 'age': 18},
  51. {'name': 'Bob', 'age': 21},
  52. {'name': 'Carol'},
  53. ]
  54. table = ui.table(columns=columns, rows=rows, row_key='name').classes('w-72')
  55. table.add_slot('header', r'''
  56. <q-tr :props="props">
  57. <q-th auto-width />
  58. <q-th v-for="col in props.cols" :key="col.name" :props="props">
  59. {{ col.label }}
  60. </q-th>
  61. </q-tr>
  62. ''')
  63. table.add_slot('body', r'''
  64. <q-tr :props="props">
  65. <q-td auto-width>
  66. <q-btn size="sm" color="accent" round dense
  67. @click="props.expand = !props.expand"
  68. :icon="props.expand ? 'remove' : 'add'" />
  69. </q-td>
  70. <q-td v-for="col in props.cols" :key="col.name" :props="props">
  71. {{ col.value }}
  72. </q-td>
  73. </q-tr>
  74. <q-tr v-show="props.expand" :props="props">
  75. <q-td colspan="100%">
  76. <div class="text-left">This is {{ props.row.name }}.</div>
  77. </q-td>
  78. </q-tr>
  79. ''')
  80. @doc.demo('Show and hide columns', '''
  81. Here is an example of how to show and hide columns in a table.
  82. ''')
  83. def show_and_hide_columns():
  84. from typing import Dict
  85. columns = [
  86. {'name': 'name', 'label': 'Name', 'field': 'name', 'required': True, 'align': 'left'},
  87. {'name': 'age', 'label': 'Age', 'field': 'age', 'sortable': True},
  88. ]
  89. rows = [
  90. {'name': 'Alice', 'age': 18},
  91. {'name': 'Bob', 'age': 21},
  92. {'name': 'Carol'},
  93. ]
  94. table = ui.table(columns=columns, rows=rows, row_key='name')
  95. def toggle(column: Dict, visible: bool) -> None:
  96. column['classes'] = '' if visible else 'hidden'
  97. column['headerClasses'] = '' if visible else 'hidden'
  98. table.update()
  99. with ui.button(icon='menu'):
  100. with ui.menu(), ui.column().classes('gap-0 p-2'):
  101. for column in columns:
  102. ui.switch(column['label'], value=True, on_change=lambda e,
  103. column=column: toggle(column, e.value))
  104. @doc.demo('Table with drop down selection', '''
  105. Here is an example of how to use a drop down selection in a table.
  106. After emitting a `rename` event from the scoped slot, the `rename` function updates the table rows.
  107. ''')
  108. def table_with_drop_down_selection():
  109. from nicegui import events
  110. columns = [
  111. {'name': 'name', 'label': 'Name', 'field': 'name'},
  112. {'name': 'age', 'label': 'Age', 'field': 'age'},
  113. ]
  114. rows = [
  115. {'id': 0, 'name': 'Alice', 'age': 18},
  116. {'id': 1, 'name': 'Bob', 'age': 21},
  117. {'id': 2, 'name': 'Carol'},
  118. ]
  119. name_options = ['Alice', 'Bob', 'Carol']
  120. def rename(e: events.GenericEventArguments) -> None:
  121. for row in rows:
  122. if row['id'] == e.args['id']:
  123. row['name'] = e.args['name']
  124. ui.notify(f'Table.rows is now: {table.rows}')
  125. table = ui.table(columns=columns, rows=rows).classes('w-full')
  126. table.add_slot('body-cell-name', r'''
  127. <q-td key="name" :props="props">
  128. <q-select
  129. v-model="props.row.name"
  130. :options="''' + str(name_options) + r'''"
  131. @update:model-value="() => $parent.$emit('rename', props.row)"
  132. />
  133. </q-td>
  134. ''')
  135. table.on('rename', rename)
  136. @doc.demo('Table from Pandas DataFrame', '''
  137. You can create a table from a Pandas DataFrame using the `from_pandas` method.
  138. This method takes a Pandas DataFrame as input and returns a table.
  139. ''')
  140. def table_from_pandas_demo():
  141. import pandas as pd
  142. df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
  143. ui.table.from_pandas(df).classes('max-h-40')
  144. @doc.demo('Table from Polars DataFrame', '''
  145. You can create a table from a Polars DataFrame using the `from_polars` method.
  146. This method takes a Polars DataFrame as input and returns a table.
  147. ''')
  148. def table_from_polars_demo():
  149. import polars as pl
  150. df = pl.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
  151. ui.table.from_polars(df).classes('max-h-40')
  152. @doc.demo('Adding rows', '''
  153. It's simple to add new rows with the `add_row(dict)` and `add_rows(list[dict])` methods.
  154. With the "virtual-scroll" prop set, the table can be programmatically scrolled with the `scrollTo` JavaScript function.
  155. ''')
  156. def adding_rows():
  157. from datetime import datetime
  158. def add():
  159. table.add_row({'date': datetime.now().strftime('%c')})
  160. table.run_method('scrollTo', len(table.rows)-1)
  161. columns = [{'name': 'date', 'label': 'Date', 'field': 'date'}]
  162. table = ui.table(columns=columns, rows=[]).classes('h-52').props('virtual-scroll')
  163. ui.button('Add row', on_click=add)
  164. @doc.demo('Custom sorting and formatting', '''
  165. You can define dynamic column attributes using a `:` prefix.
  166. This way you can define custom sorting and formatting functions.
  167. The following example allows sorting the `name` column by length.
  168. The `age` column is formatted to show the age in years.
  169. ''')
  170. def custom_formatting():
  171. columns = [
  172. {
  173. 'name': 'name',
  174. 'label': 'Name',
  175. 'field': 'name',
  176. 'sortable': True,
  177. ':sort': '(a, b, rowA, rowB) => b.length - a.length',
  178. },
  179. {
  180. 'name': 'age',
  181. 'label': 'Age',
  182. 'field': 'age',
  183. ':format': 'value => value + " years"',
  184. },
  185. ]
  186. rows = [
  187. {'name': 'Alice', 'age': 18},
  188. {'name': 'Bob', 'age': 21},
  189. {'name': 'Carl', 'age': 42},
  190. ]
  191. ui.table(columns=columns, rows=rows, row_key='name')
  192. @doc.demo('Toggle fullscreen', '''
  193. You can toggle the fullscreen mode of a table using the `toggle_fullscreen()` method.
  194. ''')
  195. def toggle_fullscreen():
  196. table = ui.table(
  197. columns=[{'name': 'name', 'label': 'Name', 'field': 'name'}],
  198. rows=[{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}],
  199. ).classes('w-full')
  200. with table.add_slot('top-left'):
  201. def toggle() -> None:
  202. table.toggle_fullscreen()
  203. button.props('icon=fullscreen_exit' if table.is_fullscreen else 'icon=fullscreen')
  204. button = ui.button('Toggle fullscreen', icon='fullscreen', on_click=toggle).props('flat')
  205. @doc.demo('Pagination', '''
  206. You can provide either a single integer or a dictionary to define pagination.
  207. The dictionary can contain the following keys:
  208. - `rowsPerPage`: The number of rows per page.
  209. - `sortBy`: The column name to sort by.
  210. - `descending`: Whether to sort in descending order.
  211. - `page`: The current page (1-based).
  212. ''')
  213. def pagination() -> None:
  214. columns = [
  215. {'name': 'name', 'label': 'Name', 'field': 'name', 'required': True, 'align': 'left'},
  216. {'name': 'age', 'label': 'Age', 'field': 'age', 'sortable': True},
  217. ]
  218. rows = [
  219. {'name': 'Elsa', 'age': 18},
  220. {'name': 'Oaken', 'age': 46},
  221. {'name': 'Hans', 'age': 20},
  222. {'name': 'Sven'},
  223. {'name': 'Olaf', 'age': 4},
  224. {'name': 'Anna', 'age': 17},
  225. ]
  226. ui.table(columns=columns, rows=rows, pagination=3)
  227. ui.table(columns=columns, rows=rows, pagination={'rowsPerPage': 4, 'sortBy': 'age', 'page': 2})
  228. @doc.demo('Handle pagination changes', '''
  229. You can handle pagination changes using the `on_pagination_change` parameter.
  230. ''')
  231. def handle_pagination_changes() -> None:
  232. ui.table(
  233. columns=[{'id': 'Name', 'label': 'Name', 'field': 'Name', 'align': 'left'}],
  234. rows=[{'Name': f'Person {i}'} for i in range(100)],
  235. pagination=3,
  236. on_pagination_change=lambda e: ui.notify(e.value),
  237. )
  238. @doc.demo('Computed props', '''
  239. You can access the computed props of a table within async callback functions.
  240. ''')
  241. def computed_props():
  242. async def show_filtered_sorted_rows():
  243. ui.notify(await table.get_filtered_sorted_rows())
  244. async def show_computed_rows():
  245. ui.notify(await table.get_computed_rows())
  246. table = ui.table(
  247. columns=[
  248. {'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left', 'sortable': True},
  249. {'name': 'age', 'label': 'Age', 'field': 'age', 'align': 'left', 'sortable': True}
  250. ],
  251. rows=[
  252. {'name': 'Noah', 'age': 33},
  253. {'name': 'Emma', 'age': 21},
  254. {'name': 'Rose', 'age': 88},
  255. {'name': 'James', 'age': 59},
  256. {'name': 'Olivia', 'age': 62},
  257. {'name': 'Liam', 'age': 18},
  258. ],
  259. row_key='name',
  260. pagination=3,
  261. )
  262. ui.input('Search by name/age').bind_value(table, 'filter')
  263. ui.button('Show filtered/sorted rows', on_click=show_filtered_sorted_rows)
  264. ui.button('Show computed rows', on_click=show_computed_rows)
  265. @doc.demo('Computed fields', '''
  266. You can use functions to compute the value of a column.
  267. The function receives the row as an argument.
  268. See the [Quasar documentation](https://quasar.dev/vue-components/table#defining-the-columns) for more information.
  269. ''')
  270. def computed_fields():
  271. columns = [
  272. {'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left'},
  273. {'name': 'length', 'label': 'Length', ':field': 'row => row.name.length'},
  274. ]
  275. rows = [
  276. {'name': 'Alice'},
  277. {'name': 'Bob'},
  278. {'name': 'Christopher'},
  279. ]
  280. ui.table(columns=columns, rows=rows, row_key='name')
  281. @doc.demo('Conditional formatting', '''
  282. You can use scoped slots to conditionally format the content of a cell.
  283. See the [Quasar documentation](https://quasar.dev/vue-components/table#example--body-cell-slot)
  284. for more information about body-cell slots.
  285. In this demo we use a `q-badge` to display the age in red if the person is under 21 years old.
  286. We use the `body-cell-age` slot to insert the `q-badge` into the `age` column.
  287. The ":color" attribute of the `q-badge` is set to "red" if the age is under 21, otherwise it is set to "green".
  288. The colon in front of the "color" attribute indicates that the value is a JavaScript expression.
  289. ''')
  290. def conditional_formatting():
  291. columns = [
  292. {'name': 'name', 'label': 'Name', 'field': 'name'},
  293. {'name': 'age', 'label': 'Age', 'field': 'age'},
  294. ]
  295. rows = [
  296. {'name': 'Alice', 'age': 18},
  297. {'name': 'Bob', 'age': 21},
  298. {'name': 'Carol', 'age': 42},
  299. ]
  300. table = ui.table(columns=columns, rows=rows, row_key='name')
  301. table.add_slot('body-cell-age', '''
  302. <q-td key="age" :props="props">
  303. <q-badge :color="props.value < 21 ? 'red' : 'green'">
  304. {{ props.value }}
  305. </q-badge>
  306. </q-td>
  307. ''')
  308. @doc.demo('Table cells with links', '''
  309. Here is a demo of how to insert links into table cells.
  310. We use the `body-cell-link` slot to insert an `<a>` tag into the `link` column.
  311. ''')
  312. def table_cells_with_links():
  313. columns = [
  314. {'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left'},
  315. {'name': 'link', 'label': 'Link', 'field': 'link', 'align': 'left'},
  316. ]
  317. rows = [
  318. {'name': 'Google', 'link': 'https://google.com'},
  319. {'name': 'Facebook', 'link': 'https://facebook.com'},
  320. {'name': 'Twitter', 'link': 'https://twitter.com'},
  321. ]
  322. table = ui.table(columns=columns, rows=rows, row_key='name')
  323. table.add_slot('body-cell-link', '''
  324. <q-td :props="props">
  325. <a :href="props.value">{{ props.value }}</a>
  326. </q-td>
  327. ''')
  328. @doc.demo('Table with masonry-like grid', '''
  329. You can use the `grid` prop to display the table as a masonry-like grid.
  330. See the [Quasar documentation](https://quasar.dev/vue-components/table#grid-style) for more information.
  331. ''')
  332. def table_with_masonry_like_grid():
  333. columns = [
  334. {'name': 'name', 'label': 'Name', 'field': 'name'},
  335. {'name': 'age', 'label': 'Age', 'field': 'age'},
  336. ]
  337. rows = [
  338. {'name': 'Alice', 'age': 18},
  339. {'name': 'Bob', 'age': 21},
  340. {'name': 'Carol', 'age': 42},
  341. ]
  342. table = ui.table(columns=columns, rows=rows, row_key='name').props('grid')
  343. table.add_slot('item', r'''
  344. <q-card flat bordered :props="props" class="m-1">
  345. <q-card-section class="text-center">
  346. <strong>{{ props.row.name }}</strong>
  347. </q-card-section>
  348. <q-separator />
  349. <q-card-section class="text-center">
  350. <div>{{ props.row.age }} years</div>
  351. </q-card-section>
  352. </q-card>
  353. ''')
  354. doc.reference(ui.table)