flet-dev / flet-dev/flet

flet.DataTable control's some problem

Open
#1,860 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
17k
Forks
694
Avg merge
1d 14h
Merged PRs (30d)
33

Description

Description

I'm experiencing issues with the DataTable control in Flet. Specifically, I'm unable to control the height of the DataTable and set up scrolling. Additionally, there is significant lag when switching to the DataTable that loads data from a CSV file after navigating from another tab.

Code example to reproduce the issue:

import flet as ft
import pandas as pd
import plotly.express as px
from flet.matplotlib_chart import MatplotlibChart
import matplotlib
import matplotlib.pyplot as plt
from adjustText import adjust_text

plt.rcParams['font.sans-serif'] = ['SimHei']  # Use SimHei font
plt.rcParams['axes.unicode_minus'] = False
from flet import (
    ElevatedButton,
    FilePicker,
    FilePickerResultEvent,
    Page,
    Row,
    Text,
    icons,
)

def df_to_dt(df):
    return ft.DataTable(
        heading_row_height= 20,
        column_spacing=20,
        data_row_max_height =30,
        columns=[ft.DataColumn(ft.Text(col)) for col in df.columns],
        rows=[
            ft.DataRow(
                cells=[
                    ft.DataCell(ft.Text(rows[1][col]))
                    for col in rows[1].index
                ]
            )
            for rows in df.iterrows()],

    )
def df_to_highlimit(df):
    first_column = df.iloc[:, 0]  # This gets the first column of the DataFrame

    return ft.LineChartData(

            data_points = [ft.LineChartDataPoint(index, value) for index, value in first_column.iteritems()],
            stroke_width=5,
            color=ft.colors.CYAN,
            curved=True,
            stroke_cap_round=True,
        )
ta = ft.DataTable()

def main(page: Page):
    # Pick files dialog
    def pick_files_result(e: FilePickerResultEvent):
        selected_files.value = (
            ", ".join(map(lambda f: f.name, e.files)) if e.files else "Cancelled!"
        )
        print(type(e.files[0].path))
        try:
            df = pd.read_csv(e.files[0].path,encoding='gbk')
        except:
            df = pd.read_csv(e.files[0].path,encoding='utf-8')
        print(df)
        t.tabs[1].content = df_to_dt(df)
        # fig = px.line(df,y='Vd下限灰阶')
        fig, ax = plt.subplots(figsize=(12, 6))
        ax.plot(df.index, df['Vd上限灰阶'],color='g')
        ax2 = ax.twinx()
        df['Vd上限灰阶差'] = df['Vd上限灰阶']-df['Vd上限灰阶'].shift(-1)
        ax2.plot(df.index, df['Vd上限灰阶差'] ,color='b')
        ax2.set_ylabel('灰阶差', color='b')
        texts = []
        for x, y, z in zip(df.index, df['Vd上限灰阶'], df['Vd上限灰阶差']):
            ax2.annotate(str(round(y, 2)), (x, z), textcoords="offset points", xytext=(0, 10), ha='center', color='red',rotation=60,)
        ax.grid(True)
        ax.set_ylabel("灰阶")
        ax.set_title("Vd下限灰阶")
        # ax.legend(title="Vd上限灰阶")
        # ax2.legend(title="Vd上限灰阶差")

        t.tabs[0].content = MatplotlibChart(fig,expand = True)

        page.update()
        selected_files.update()

    pick_files_dialog = FilePicker(on_result=pick_files_result)
    selected_files = Text()

    # Save file dialog
    def save_file_result(e: FilePickerResultEvent):
        save_file_path.value = e.path if e.path else "Cancelled!"
        save_file_path.update()

    save_file_dialog = FilePicker(on_result=save_file_result)
    save_file_path = Text()

    # Open directory dialog
    def get_directory_result(e: FilePickerResultEvent):
        directory_path.value = e.path if e.path else "Cancelled!"
        directory_path.update()

    get_directory_dialog = FilePicker(on_result=get_directory_result)
    directory_path = Text()


    t = ft.Tabs(
        selected_index=1,
        animation_duration=300,

        tabs=[
            ft.Tab(
                text="窗口计算",
                content=ft.Container(
                    content=MatplotlibChart(),
                    alignment=ft.alignment.center
                ),
            ),
            ft.Tab(
                tab_content=ft.Icon(ft.icons.DATASET),
                content=ft.DataTable(),
            ),
            ft.Tab(
                text="Tab 3",
                icon=ft.icons.SETTINGS,
                content=ft.Text("This is Tab 3"),
            ),
        ],
        scrollable=True,

        expand=1,
    )
    # hide all dialogs in overlay
    page.overlay.extend([pick_files_dialog, save_file_dialog, get_directory_dialog])


    # page.add(
    #                 t
    #
    # )

    page.add(

        ft.Column(
            [
                ft.Row([
                ElevatedButton(
                    "Pick files",
                    icon=icons.UPLOAD_FILE,
                    on_click=lambda _: pick_files_dialog.pick_files(
                        allow_multiple=True
                    ),
                ),
                selected_files,
                ElevatedButton(
                    "计算窗口",
                    icon=icons.FOLDER_OPEN,
                    on_click=lambda _: get_directory_dialog.get_directory_path(),
                    disabled=page.web,
                ),
                directory_path,
            ],
        ),
                ],
        ),
        # ft.Column(
        #     [
        #         ElevatedButton(
        #             "Save file",
        #             icon=icons.SAVE,
        #             on_click=lambda _: save_file_dialog.save_file(),
        #             disabled=page.web,
        #         ),
        #         save_file_path,
        #     ]
        # ),
        # ft.Column(
        #     [
        #         ElevatedButton(
        #             "Open directory",
        #             icon=icons.FOLDER_OPEN,
        #             on_click=lambda _: get_directory_dialog.get_directory_path(),
        #             disabled=page.web,
        #         ),
        #         directory_path,
        #     ]
        # ),
        # ft.Column(
        #     [
        #         ElevatedButton(
        #             "计算窗口",
        #             icon=icons.FOLDER_OPEN,
        #             on_click=lambda _: get_directory_dialog.get_directory_path(),
        #             disabled=page.web,
        #         ),
        #         directory_path,
        #     ]
        # ),
        ft.Column(
            [

                t
            ],
        # scroll = ft.ScrollMode.ALWAYS,

    ),

    )
    page.ScrollMode = 'ALWAYS'


ft.app(target=main)

Describe the results you received:

Describe the results you expected:

Additional information you deem important (e.g. issue happens only occasionally):

Flet version (pip show flet):

0.10.1

Operating system:

Windows

Additional environment details:

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with df_to_dt(), pick_files_result(), and the Tabs definition in the provided reproduction. First isolate the DataTable height/scrolling behavior from the tab-switching lag, then confirm the expected dimensions, scrolling behavior, and performance target with a minimal example. Done should mean both reported problems are reproduced and addressed or documented with clear results.

Written by the indexing model from the issue text.

Assessment

Tech stack
matplotlib, pandas, python
Domain
frontend, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.