Search code examples
pythondatatableflet

How do I edit a cell in flet's DataTable?


Flet's DataTable has a show_edit_icon property, but I don't know how do something when the icon is pressed.

This is an example code:

import flet as ft

def main(page: ft.Page):
    page.add(
        ft.DataTable(
            columns=[
                ft.DataColumn(ft.Text("First name")),
                ft.DataColumn(ft.Text("Last name")),
            ],
            rows=[
                ft.DataRow(
                    cells=[
                        ft.DataCell(ft.Text("John"), show_edit_icon=True),
                        ft.DataCell(ft.Text("Smith")),
                    ],
                ),
            ],
        ),
    )

ft.app(target=main, view=ft.WEB_BROWSER)

I see the edit icon, but how do I connect it to some function that receives the cell that is being edited?


Solution

  • As per the doccumentation, In FLET data table, show_edit_icon This will only enable you to see the cell's icon. nonetheless, You must create a new function and connect it to the cell on on_tap functionality.

    Note:

    • Add property on_tap to the the cell

    • implement a new function

    • Update the page after change inside the new function

      import flet as ft
      
       def main(page: ft.Page):
           # this is the function that controls the value of the cell 
           # returns value on tap
           def updateOnTap(e):
             e.control.content.value = "Hello John"
             page.update()
      
           page.add(
               ft.DataTable(
                   columns=[
                       ft.DataColumn(ft.Text("First name")),
                       ft.DataColumn(ft.Text("Last name")),
                   ],
                   rows=[
                       ft.DataRow(
                           cells=[
                               ft.DataCell(ft.Text("John"), show_edit_icon=True, on_tap=updateOnTap),
                               ft.DataCell(ft.Text("Smith")),
                           ],
                       ),
                   ],
               ),
           )
      
       ft.app(target=main, view=ft.WEB_BROWSER)