Getting the selected cells from a wxPython grid

Getting the selected cells from a wxPython grid is a little tricky, because you have to use a different method depending on which of the following scenarios applies:

  1. A single cell has been selected
  2. Multiple cells have been selected via Control+Clicking
  3. A range of cells has been selected via dragging

The following two functions will return a list of (row, column) pairs representing the selected cell(s) in any of the above cases.

def corners_to_cells(top_lefts, bottom_rights):
    """
    Take lists of top left and bottom right corners, and
    return a list of all the cells in that range
    "
""

    cells = []
    for top_left, bottom_right in zip(top_lefts, bottom_rights):

        rows_start = top_left[0]
        rows_end = bottom_right[0]

        cols_start = top_left[1]
        cols_end = bottom_right[1]

        rows = range(rows_start, rows_end+1)
        cols = range(cols_start, cols_end+1)

        cells.extend([(row, col)
            for row in rows
            for col in cols])

    return cells

def get_selected_cells(grid):
    """
    Return the selected cells in the grid as a list of
    (row, col) pairs.
    We need to take care of three possibilities:
    1. Multiple cells were click-selected (GetSelectedCells)
    2. Multiple cells were drag selected (GetSelectionBlock…)
    3. A single cell only is selected (CursorRow/Col)
    "
""

    top_left = grid.GetSelectionBlockTopLeft()

    if top_left:
        bottom_right = grid.GetSelectionBlockBottomRight()
        return corners_to_cells(top_left, bottom_right)

    selection = grid.GetSelectedCells()

    if not selection:
        row = grid.GetGridCursorRow()
        col = grid.GetGridCursorCol()
        return [(row, col)]

    return selection

4 comments to Getting the selected cells from a wxPython grid

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>