1

When using wx.grid for creating table with wxpython, how can I automatically extend the number of rows and columns in the table once the user resizes the frame?

If I create 5*5 table(grid) to fit on my frame and user resizes the frame( say, makes it bigger), how can I implement automatic increase to the number of rows and/or column which responds to increase in frame size?

4
  • Are you sure that you can't just use clipping of the grid itself for the effect you want? The sizer layout model would allow you to crop the grid to fit the region; simply add all of the rows/columns, and allow the size of the window to constrain the area that is visible…
    – BRPocock
    Feb 10, 2012 at 15:24
  • Sorry if I understand you incorrectly..Do you mean to setup a table with 1000*1000 and clipp it with sizer to show say, 20*20 and when user increases the size of the table, they will see more? If that is what you are saying, doesn't that take more memory than what user really might need? Feb 10, 2012 at 15:33
  • 1
    Essentially, yes. Although it entirely depends on what you're doing with the wxGrid. If you are intentionally handling scrolling/paging yourself, that's fine, but wxWidgets is designed for you to create the grid at its full size, and use sizers and other widgets to handle clipping and scrolling. As @Mike Driscoll indicates, below, you do have hooks to “re-invent those wheels,” but that's not how the framework is designed to be used in general.
    – BRPocock
    Feb 10, 2012 at 15:42
  • @Jack_of_All_Trades, why you want to do that? It will be easier to make the grid table with whatever size is needed and not increase it on resizing.
    – Igor
    Jan 19 at 14:03

2 Answers 2

1

Sadly there is no builtin way to do this that I'm aware of. You'll need to catch the frame's EVT_SIZE and then use AppendRows and AppendCols as necessary with the grid. You'll need to take into account how much the frame size has changed and only append when it gets bigger, not smaller.

0

Try this,and the function of sorting by clicking on the header has been added:

import wx 
import wx.grid

class Table123(wx.grid.Grid):
    def __init__(self, parent, rows=[], columns=[], pagination=None):
        super(Table123, self).__init__(parent)
        if pagination is None:
            pagination = {
                'sortBy': '',
                'descending': False,
                'page': 1,
                'rowsPerPage': 10,
                'rowsNumber': 10
            }
        self.columns = columns
        self.rows = rows
        self.pagination = pagination
        self.SetDefaultCellAlignment(wx.ALIGN_CENTER, wx.ALIGN_CENTER)
        self.CreateGrid(len(self.rows), len(self.columns))
        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.on_label_click)
        self.populate_grid()
        self.HideRowLabels()
        self.Bind(wx.EVT_SIZE, self.on_size)
        self.on_size()

    def populate_grid(self):
        for index, column in enumerate(self.columns):
            self.SetColLabelValue(index, column.get("label",""))
        for col in range(self.GetNumberCols()):
            label = self.GetColLabelValue(col)
            self.SetColLabelValue(col, f"{label} {self.get_sort_indicator(col)}")
        for row_index, row in enumerate(self.rows):
            for col_index, column in enumerate(self.columns):
                self.SetCellValue(row_index, col_index, str(row.get(column.get("name",""),"")))

    def on_label_click(self, event):
        col = event.GetCol()
        column_dict = self.columns[col]
        col_name = column_dict.get("name","")
        if self.pagination.get("sortby","") == col_name:
            self.pagination["descending"] = not self.pagination.get("descending","")
        else:
            self.pagination["sortby"] = col_name
            self.pagination["descending"] = False

        self.sort_data(col_name)
        self.ClearGrid()
        self.populate_grid()

    def on_size(self, event=None):
        width, height = self.GetClientSize()
        self.AutoSizeColumns()
        current_col_widths = [self.GetColSize(col) for col in range(self.GetNumberCols())]
        total_width = sum(current_col_widths)
        for col, column_info in enumerate(self.columns):
            relative_width = current_col_widths[col] / total_width
            col_width = int(width * relative_width)
            self.SetColSize(col, col_width)

    def sort_data(self, key):
        self.rows.sort(key=lambda x: x[key], reverse=(self.pagination.get("descending",False)))

    def get_sort_indicator(self, col):
        if self.pagination.get("sortby") == self.columns[col].get("name"):
            return "↑" if self.pagination.get("descending") else "↓"
        return ""

class MyFrame(wx.Frame):
    def __init__(self, *args, **kw):
        super(MyFrame, self).__init__(*args, **kw)
        self.Maximize()
        panel = wx.Panel(self)
        data = [
            {'name': 'Alice', 'age': 25, 'city': 'New York'},
            {'name': 'Bob', 'age': 30, 'city': 'San Franciscoooooooooooooooooooooooooo'},
            {'name': 'Charlie', 'age': 22, 'city': 'Seattle'},
        ]
        columns = [
            {'name': 'name', 'label': 'FirstName'},
            {'name': 'age', 'label': 'Age'},
            {'name': 'city', 'label': 'City'},
        ]
        grid = Table123(panel, rows=data, columns=columns)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 1, wx.EXPAND)
        panel.SetSizer(sizer)

        self.SetSize((600, 400))
        self.Center()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame(None, title="Grid Example")
    frame.Show()
    app.MainLoop()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.