1
0

table_documentation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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('Adding rows', '''
  145. It's simple to add new rows with the `add_row(dict)` and `add_rows(list[dict])` methods.
  146. With the "virtual-scroll" prop set, the table can be programmatically scrolled with the `scrollTo` JavaScript function.
  147. ''')
  148. def adding_rows():
  149. from datetime import datetime
  150. def add():
  151. table.add_row({'date': datetime.now().strftime('%c')})
  152. table.run_method('scrollTo', len(table.rows)-1)
  153. columns = [{'name': 'date', 'label': 'Date', 'field': 'date'}]
  154. table = ui.table(columns=columns, rows=[]).classes('h-52').props('virtual-scroll')
  155. ui.button('Add row', on_click=add)
  156. @doc.demo('Custom sorting and formatting', '''
  157. You can define dynamic column attributes using a `:` prefix.
  158. This way you can define custom sorting and formatting functions.
  159. The following example allows sorting the `name` column by length.
  160. The `age` column is formatted to show the age in years.
  161. ''')
  162. def custom_formatting():
  163. columns = [
  164. {
  165. 'name': 'name',
  166. 'label': 'Name',
  167. 'field': 'name',
  168. 'sortable': True,
  169. ':sort': '(a, b, rowA, rowB) => b.length - a.length',
  170. },
  171. {
  172. 'name': 'age',
  173. 'label': 'Age',
  174. 'field': 'age',
  175. ':format': 'value => value + " years"',
  176. },
  177. ]
  178. rows = [
  179. {'name': 'Alice', 'age': 18},
  180. {'name': 'Bob', 'age': 21},
  181. {'name': 'Carl', 'age': 42},
  182. ]
  183. ui.table(columns=columns, rows=rows, row_key='name')
  184. @doc.demo('Toggle fullscreen', '''
  185. You can toggle the fullscreen mode of a table using the `toggle_fullscreen()` method.
  186. ''')
  187. def toggle_fullscreen():
  188. table = ui.table(
  189. columns=[{'name': 'name', 'label': 'Name', 'field': 'name'}],
  190. rows=[{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Carol'}],
  191. ).classes('w-full')
  192. with table.add_slot('top-left'):
  193. def toggle() -> None:
  194. table.toggle_fullscreen()
  195. button.props('icon=fullscreen_exit' if table.is_fullscreen else 'icon=fullscreen')
  196. button = ui.button('Toggle fullscreen', icon='fullscreen', on_click=toggle).props('flat')
  197. @doc.demo('Pagination', '''
  198. You can provide either a single integer or a dictionary to define pagination.
  199. The dictionary can contain the following keys:
  200. - `rowsPerPage`: The number of rows per page.
  201. - `sortBy`: The column name to sort by.
  202. - `descending`: Whether to sort in descending order.
  203. - `page`: The current page (1-based).
  204. ''')
  205. def pagination() -> None:
  206. columns = [
  207. {'name': 'name', 'label': 'Name', 'field': 'name', 'required': True, 'align': 'left'},
  208. {'name': 'age', 'label': 'Age', 'field': 'age', 'sortable': True},
  209. ]
  210. rows = [
  211. {'name': 'Elsa', 'age': 18},
  212. {'name': 'Oaken', 'age': 46},
  213. {'name': 'Hans', 'age': 20},
  214. {'name': 'Sven'},
  215. {'name': 'Olaf', 'age': 4},
  216. {'name': 'Anna', 'age': 17},
  217. ]
  218. ui.table(columns=columns, rows=rows, pagination=3)
  219. ui.table(columns=columns, rows=rows, pagination={'rowsPerPage': 4, 'sortBy': 'age', 'page': 2})
  220. @doc.demo('Handle pagination changes', '''
  221. You can handle pagination changes using the `on_pagination_change` parameter.
  222. ''')
  223. def handle_pagination_changes() -> None:
  224. ui.table(
  225. columns=[{'id': 'Name', 'label': 'Name', 'field': 'Name', 'align': 'left'}],
  226. rows=[{'Name': f'Person {i}'} for i in range(100)],
  227. pagination=3,
  228. on_pagination_change=lambda e: ui.notify(e.value),
  229. )
  230. @doc.demo('Computed props', '''
  231. You can access the computed props of a table within async callback functions.
  232. ''')
  233. def computed_props():
  234. async def show_filtered_sorted_rows():
  235. ui.notify(await table.get_filtered_sorted_rows())
  236. async def show_computed_rows():
  237. ui.notify(await table.get_computed_rows())
  238. table = ui.table(
  239. columns=[
  240. {'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left', 'sortable': True},
  241. {'name': 'age', 'label': 'Age', 'field': 'age', 'align': 'left', 'sortable': True}
  242. ],
  243. rows=[
  244. {'name': 'Noah', 'age': 33},
  245. {'name': 'Emma', 'age': 21},
  246. {'name': 'Rose', 'age': 88},
  247. {'name': 'James', 'age': 59},
  248. {'name': 'Olivia', 'age': 62},
  249. {'name': 'Liam', 'age': 18},
  250. ],
  251. row_key='name',
  252. pagination=3,
  253. )
  254. ui.input('Search by name/age').bind_value(table, 'filter')
  255. ui.button('Show filtered/sorted rows', on_click=show_filtered_sorted_rows)
  256. ui.button('Show computed rows', on_click=show_computed_rows)
  257. @doc.demo('Computed fields', '''
  258. You can use functions to compute the value of a column.
  259. The function receives the row as an argument.
  260. See the [Quasar documentation](https://quasar.dev/vue-components/table#defining-the-columns) for more information.
  261. ''')
  262. def computed_fields():
  263. columns = [
  264. {'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left'},
  265. {'name': 'length', 'label': 'Length', ':field': 'row => row.name.length'},
  266. ]
  267. rows = [
  268. {'name': 'Alice'},
  269. {'name': 'Bob'},
  270. {'name': 'Christopher'},
  271. ]
  272. ui.table(columns=columns, rows=rows, row_key='name')
  273. @doc.demo('Conditional formatting', '''
  274. You can use scoped slots to conditionally format the content of a cell.
  275. See the [Quasar documentation](https://quasar.dev/vue-components/table#example--body-cell-slot)
  276. for more information about body-cell slots.
  277. In this demo we use a `q-badge` to display the age in red if the person is under 21 years old.
  278. We use the `body-cell-age` slot to insert the `q-badge` into the `age` column.
  279. The ":color" attribute of the `q-badge` is set to "red" if the age is under 21, otherwise it is set to "green".
  280. The colon in front of the "color" attribute indicates that the value is a JavaScript expression.
  281. ''')
  282. def conditional_formatting():
  283. columns = [
  284. {'name': 'name', 'label': 'Name', 'field': 'name'},
  285. {'name': 'age', 'label': 'Age', 'field': 'age'},
  286. ]
  287. rows = [
  288. {'name': 'Alice', 'age': 18},
  289. {'name': 'Bob', 'age': 21},
  290. {'name': 'Carol', 'age': 42},
  291. ]
  292. table = ui.table(columns=columns, rows=rows, row_key='name')
  293. table.add_slot('body-cell-age', '''
  294. <q-td key="age" :props="props">
  295. <q-badge :color="props.value < 21 ? 'red' : 'green'">
  296. {{ props.value }}
  297. </q-badge>
  298. </q-td>
  299. ''')
  300. @doc.demo('Table cells with links', '''
  301. Here is a demo of how to insert links into table cells.
  302. We use the `body-cell-link` slot to insert an `<a>` tag into the `link` column.
  303. ''')
  304. def table_cells_with_links():
  305. columns = [
  306. {'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left'},
  307. {'name': 'link', 'label': 'Link', 'field': 'link', 'align': 'left'},
  308. ]
  309. rows = [
  310. {'name': 'Google', 'link': 'https://google.com'},
  311. {'name': 'Facebook', 'link': 'https://facebook.com'},
  312. {'name': 'Twitter', 'link': 'https://twitter.com'},
  313. ]
  314. table = ui.table(columns=columns, rows=rows, row_key='name')
  315. table.add_slot('body-cell-link', '''
  316. <q-td :props="props">
  317. <a :href="props.value">{{ props.value }}</a>
  318. </q-td>
  319. ''')
  320. @doc.demo('Table with masonry-like grid', '''
  321. You can use the `grid` prop to display the table as a masonry-like grid.
  322. See the [Quasar documentation](https://quasar.dev/vue-components/table#grid-style) for more information.
  323. ''')
  324. def table_with_masonry_like_grid():
  325. columns = [
  326. {'name': 'name', 'label': 'Name', 'field': 'name'},
  327. {'name': 'age', 'label': 'Age', 'field': 'age'},
  328. ]
  329. rows = [
  330. {'name': 'Alice', 'age': 18},
  331. {'name': 'Bob', 'age': 21},
  332. {'name': 'Carol', 'age': 42},
  333. ]
  334. table = ui.table(columns=columns, rows=rows, row_key='name').props('grid')
  335. table.add_slot('item', r'''
  336. <q-card flat bordered :props="props" class="m-1">
  337. <q-card-section class="text-center">
  338. <strong>{{ props.row.name }}</strong>
  339. </q-card-section>
  340. <q-separator />
  341. <q-card-section class="text-center">
  342. <div>{{ props.row.age }} years</div>
  343. </q-card-section>
  344. </q-card>
  345. ''')
  346. doc.reference(ui.table)