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:
- A single cell has been selected
- Multiple cells have been selected via Control+Clicking
- 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.
"""
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
