KivyMD icon indicating copy to clipboard operation
KivyMD copied to clipboard

Add API to change active property of MDDataTable checkboxes from code

Open Kak0ytachel opened this issue 1 year ago • 0 comments

Description of the Feature

There are no API to change active property of MDDataTable checkboxes from code, you can only get checked rows using get_row_checks() or handle the on_check_press event, which is called when the check box in the table row is checked, but not change the checks. In my opinion, this feature is really necessary in many cases, for example to handle removing checked rows, because after removing a row it's checkbox stays active, so it should be added

Code and Logs

import random

from kivy.metrics import dp

from kivymd.app import MDApp
from kivymd.uix.datatables import MDDataTable
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.button import MDRaisedButton

class Example(MDApp):
    data_tables = None

    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Orange"

        layout = MDFloatLayout()
        button_box = MDBoxLayout(
            pos_hint={"center_x": 0.5},
            adaptive_size=True,
            padding="24dp",
            spacing="24dp",
        )

        for button_text in ["Add row", "Remove checked rows"]:
            button_box.add_widget(
                MDRaisedButton(
                    text=button_text, on_release=self.on_button_press
                )
            )

        self.data_tables = MDDataTable(
            pos_hint={"center_y": 0.5, "center_x": 0.5},
            check=True,
            size_hint=(0.9, 0.6),
            use_pagination=False,
            column_data=[
                ("No.", dp(30)),
                ("Column 1", dp(40)),
                ("Column 2", dp(40)),
                ("Column 3", dp(40)),
            ],
            row_data=[["1", "1", "2", "3"]],
        )
        layout.add_widget(self.data_tables)
        layout.add_widget(button_box)

        return layout

    def on_button_press(self, instance_button: MDRaisedButton) -> None:

        try:
            {
                "Add row": self.add_row,
                "Remove checked rows": self.remove_row,
            }[instance_button.text]()
        except KeyError:
            pass

    def add_row(self) -> None:
        self.data_tables.add_row([str(random.randint(1, 100)), "1", "2", "3"])

    def remove_row(self) -> None:
        print('all_rows: '+ str(self.data_tables.row_data))
        for row in self.data_tables.get_row_checks():
            print(row)
            self.data_tables.remove_row(row)


Example().run()

Versions

  • OS: win10
  • Python: 3.9
  • Kivy: 2.1.0
  • KivyMD: 1.2.0.dev0 (master branch)

Kak0ytachel avatar Nov 14 '22 20:11 Kak0ytachel