Prechádzať zdrojové kódy

Add an editable table example, getrowids for aggrid

Dronakurl 1 rok pred
rodič
commit
860b9ead64

+ 84 - 0
examples/editable_table/main.py

@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+from nicegui import ui, events
+        
+columns = [
+    {"name": "name", "label": "Name", "field": "name", "align": "left"},
+    {"name": "age", "label": "Age", "field": "age"},
+]
+rows = [
+    {"id": 0, "name": "Alice", "age": 18},
+    {"id": 1, "name": "Bob", "age": 21},
+    {"id": 2, "name": "Carol", "age": 20},
+]
+def rename(e: events.GenericEventArguments) -> None:
+    for row in rows:
+        if row["id"] == e.args["id"]:
+            row.update(e.args)
+    ui.notify(f"Table.rows is now: {table.rows}")
+
+
+def delete(e: events.GenericEventArguments) -> None:
+    rows[:] = [row for row in rows if row["id"] != e.args["id"]]
+    ui.notify(f"Delete {e.args['id']}")
+    table.update()
+
+
+def addrow() -> None:
+    newid = max(dx["id"] for dx in rows) + 1
+    rows.append({"id": newid, "name": "New guy", "age": 21})
+    ui.notify(f"Added new row with id {newid}")
+    table.update()
+
+
+table = ui.table(columns=columns, rows=rows, row_key="name").classes("w-72")
+table.add_slot(
+    "header",
+    r"""
+    <q-tr :props="props">
+        <q-th auto-width />
+        <q-th v-for="col in props.cols" :key="col.name" :props="props">
+            {{ col.label }}
+        </q-th>
+    </q-tr>
+""",
+)
+table.add_slot(
+    "body",
+    r"""
+    <q-tr :props="props">
+        <q-td auto-width >
+            <q-btn size="sm" color="warning" round dense icon="delete" :props="props"
+                @click="() => $parent.$emit('delete', props.row)" >
+        </q-td>
+        <q-td key="name" :props="props">
+            {{ props.row.name }}
+            <q-popup-edit v-model="props.row.name" v-slot="scope" 
+                @update:model-value="() => $parent.$emit('rename', props.row)" >
+                <q-input v-model="scope.value" dense autofocus counter @keyup.enter="scope.set" />
+            </q-popup-edit>
+        </q-td>
+        <q-td key="age" :props="props" class="w-8">
+            {{ props.row.age }}
+            <q-popup-edit v-model="props.row.age" v-slot="scope" 
+                @update:model-value="() => $parent.$emit('rename', props.row)" >
+                <q-input v-model.number="scope.value" type="number" dense autofocus counter @keyup.enter="scope.set" />
+            </q-popup-edit>
+        </q-td>
+    </q-tr>
+    """,
+)
+table.add_slot(
+    "bottom-row",
+    r"""
+    <q-tr :props="props">
+        <q-td colspan="3" class="text-center">
+            <q-btn color="accent" icon="add" class="w-full" @click="() => $parent.$emit('addrow')"/>
+        </q-td>
+    </q-tr>
+    """,
+)
+table.on("rename", rename)
+table.on("delete", delete)
+table.on("addrow", addrow)
+
+ui.run()

+ 1 - 0
main.py

@@ -364,6 +364,7 @@ async def index_page(client: Client) -> None:
             example_link('Generate PDF', 'create SVG preview and PDF download from input form elements')
             example_link('Custom Binding', 'create a custom binding for a label with a bindable background color')
             example_link('Descope Auth', 'login form and user profile using [Descope](https://descope.com)')
+            example_link('Editable table', 'editable table with editing, removing and add new rows')
 
     with ui.row().classes('dark-box min-h-screen mt-16'):
         link_target('why')

+ 14 - 0
nicegui/elements/aggrid.py

@@ -126,6 +126,20 @@ class AgGrid(Element, component='aggrid.js', libraries=['lib/aggrid/ag-grid-comm
         result = await self.call_api_method('getSelectedRows')
         return cast(List[Dict], result)
 
+    async def get_selected_row_ids(self) -> List[int]:
+        """Get the currently selected rows ids (or nodes in AG Grid)
+
+        This method is useful when the grid is configured with ``rowSelection: 'multiple'``.
+        It returns only the ids of the selected rows, which on default are set by AG Grid
+
+        See `AG Grid API <https://www.ag-grid.com/javascript-data-grid/row-selection/#reference-selection-getSelectedNodes>`_ 
+        for more information.
+
+        :return: list of selected row ids
+        """
+        result = await self.client.run_javascript(f"return getElement({self.id}).gridOptions.api.getSelectedNodes().map(x => x.id)")
+        return cast(List[int], result)
+
     async def get_selected_row(self) -> Optional[Dict]:
         """Get the single currently selected row.
 

+ 1 - 1
website/more_documentation/table_documentation.py

@@ -1,5 +1,4 @@
 from nicegui import ui
-
 from ..documentation_tools import text_demo
 
 
@@ -273,3 +272,4 @@ def more() -> None:
                 </q-badge>
             </q-td>
         ''')
+