table_documentation.py 14 KB

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