[Python-es] borde de celda wx grid
damufo
damufo en gmail.com
Dom Feb 13 11:38:29 CET 2011
Hola
En 2011/02/05 12:04, Oswaldo Hernández escribiu:
> El 05/02/2011 10:03, damufo escribió:
>> Hola:
>> Tengo un control wx.grid y me gustaría saber si alguien sabe si se puede
>> o como ponerle borde derecho a determinada celda.
>> He estado buscando y no acabo de encontrar la solución.
>>
>> Aquí
>> http://forums.wxwidgets.org/viewtopic.php?t=26838
>> comentan la cuestión pero no acabo de entender como.
>>
>> Aquí también se comenta algo:
>> http://wxpython-users.1045709.n5.nabble.com/wxgrid-cell-border-td2343244.html
>>
>>
>>
>> Alguna sugerencia?
>>
>
> Para personalizar celdas individuales tienes que hacerlo tu mismo
> utilizando el CellRenderer. En la demo de wxPython hay algún ejemplo
> de ello.
>
> Saludos,
Primeramente gracias por la ayuda.
A partir del ejemplo de la demo de wxpython, he logrado dibujar los
bordes de una celda, aunque no comprendo todo el código ya que para mi
nivel de conocimiento me pierdo, fuí logrando cosas por ensaya y error.
Al grano, resulta que tengo una clase que hereda de Grid.PyGridCellRenderer
esta es la que dibuja la celda especial (en mi caso quiero que le ponga
bordes), con el método Draw() en este caso pinta bordes, además quiero
que trate tambien celdas combinadas.
Lo que me gustaría es que antes de pintar los bordes pintase la celda
normal, y despues sobre ella pintase dichos bordes. Por ejemplo si por
defecto en alineación vertical tengo centrado quiero que así ponga el texto.
Para ello en el mi calse especial sólo he puesto el código que dibuja
los bordes y el caso es que tal como esta lo de dentro se queda sin
rellenar.
Si no me equivoco este método Draw() está sobrecargando el Draw() por
defecto, hay forma de que cuando llame mi método Draw() "modificado",
dentro de el llame antes al método Draw() por defecto (clase de la que
hereda) y despues realice las modificaciones que he puesto en mi método
sobrecargado?
Espero que se entienda. (primero pinta como si de una celda normal se
tratase y despues por encima pon estas líneas)
Realmente no se si esta es solución o hay otra mejor (de momento es la
que se me ha ocurido).
Anexo el código de esta clase y despues a continuación el código de la
prueba completa el cual es funcional por sí solo y se puede ver el error
que indico (siento poner tando código porque se que es mucho, este
ultimo lo pondría como anexo pero pienso que la lista no lo permite).
class CellRenderer(Grid.PyGridCellRenderer):
def __init__(self, table, color="red", font="ARIAL", fontsize=8):
"""Render data in the specified color and font and fontsize"""
Grid.PyGridCellRenderer.__init__(self)
self.table = table
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
# aqui es donde quería poner la llamada al Draw de la clase padre
# // pinta bordes, derecho, izquierdo, inferior, superior
dc.SetPen( wx.Pen(wx.Colour( 255, 0, 0 ) , 1, wx.SOLID))
dc.DrawLine( rect.x + rect.width-1, rect.y,
rect.x + rect.width-1, rect.y + rect.height)
dc.DrawLine( rect.x, rect.y, rect.x, rect.y + rect.height)
dc.DrawLine( rect.x, rect.y, rect.x + rect.width, rect.y)
dc.DrawLine( rect.x, rect.y + rect.height-1,
rect.x + rect.width, rect.y + rect.height-1 )
# --------------------------------------------------------------------
prueba_grid_especial.py
#aqui va el código del ejemplo completo.
'''
Created on 07/02/2011
@author: damufo
'''
import wx
import wx.grid as Grid
#---------------------------------------------------------------------------
class MegaTable(Grid.PyGridTableBase):
"""
A custom wx.Grid Table using user supplied data
"""
def __init__(self, data, colnames):
"""data is a list of the form
[(rowname, dictionary),
dictionary.get(colname, None) returns the data for column
colname
"""
# The base class must be initialized *first*
Grid.PyGridTableBase.__init__(self)
self.data = data
self.colnames = colnames
# XXX
# we need to store the row length and column length to
# see if the table has changed size
self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols()
def GetNumberCols(self):
return len(self.colnames)
def GetNumberRows(self):
return len(self.data)
def GetColLabelValue(self, col):
return self.colnames[col]
def GetRowLabelValue(self, row):
return "row %03d" % int(self.data[row][0])
def GetValue(self, row, col):
return str(self.data[row][1].get(self.GetColLabelValue(col), ""))
def GetRawValue(self, row, col):
return self.data[row][1].get(self.GetColLabelValue(col), "")
def SetValue(self, row, col, value):
self.data[row][1][self.GetColLabelValue(col)] = value
def ResetView(self, grid):
"""
(Grid) -> Reset the grid view. Call this to
update the grid if rows and columns have been added or deleted
"""
grid.BeginBatch()
for current, new, delmsg, addmsg in [
(self._rows, self.GetNumberRows(),
Grid.GRIDTABLE_NOTIFY_ROWS_DELETED, Grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),
(self._cols, self.GetNumberCols(),
Grid.GRIDTABLE_NOTIFY_COLS_DELETED, Grid.GRIDTABLE_NOTIFY_COLS_APPENDED),
]:
if new < current:
msg = Grid.GridTableMessage(self,delmsg,new,current-new)
grid.ProcessTableMessage(msg)
elif new > current:
msg = Grid.GridTableMessage(self,addmsg,new-current)
grid.ProcessTableMessage(msg)
self.UpdateValues(grid)
grid.EndBatch()
self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols()
# update the scrollbars and the displayed part of the grid
grid.AdjustScrollbars()
grid.ForceRefresh()
def UpdateValues(self, grid):
"""Update all displayed values"""
# This sends an event to the grid table to update all of the values
msg = Grid.GridTableMessage(self,
Grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
grid.ProcessTableMessage(msg)
def UpdateCellAttrs(self, grid, row, col):
"""
wx.Grid -> update the column attributes to add the
appropriate renderer given the column name. (renderers
are stored in the self.plugins dictionary)
Otherwise default to the default renderer.
"""
print row
print col
attr = Grid.GridCellAttr()
renderer = CellRenderer(self)
attr.SetRenderer(renderer)
grid.SetAttr(row, col, attr)
# ------------------------------------------------------
# begin the added code to manipulate the table (non wx related)
def AppendRow(self, row):
#print 'append'
entry = {}
for name in self.colnames:
entry[name] = "Appended_%i"%row
# XXX Hack
# entry["A"] can only be between 1..4
entry["A"] = random.choice(range(4))
self.data.insert(row, ["Append_%i"%row, entry])
def DeleteCols(self, cols):
"""
cols -> delete the columns from the dataset
cols hold the column indices
"""
# we'll cheat here and just remove the name from the
# list of column names. The data will remain but
# it won't be shown
deleteCount = 0
cols = cols[:]
cols.sort()
for i in cols:
self.colnames.pop(i-deleteCount)
# we need to advance the delete count
# to make sure we delete the right columns
deleteCount += 1
if not len(self.colnames):
self.data = []
def DeleteRows(self, rows):
"""
rows -> delete the rows from the dataset
rows hold the row indices
"""
deleteCount = 0
rows = rows[:]
rows.sort()
for i in rows:
self.data.pop(i-deleteCount)
# we need to advance the delete count
# to make sure we delete the right rows
deleteCount += 1
def SortColumn(self, col):
"""
col -> sort the data based on the column indexed by col
"""
name = self.colnames[col]
_data = []
for row in self.data:
rowname, entry = row
_data.append((entry.get(name, None), row))
_data.sort()
self.data = []
for sortvalue, row in _data:
self.data.append(row)
# end table manipulation code
# ----------------------------------------------------------
# --------------------------------------------------------------------
# Sample wx.Grid renderers
class CellRenderer(Grid.PyGridCellRenderer):
def __init__(self, table, color="red", font="ARIAL", fontsize=8):
"""Render data in the specified color and font and fontsize"""
Grid.PyGridCellRenderer.__init__(self)
self.table = table
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
# # Here we draw text in a grid cell using various fonts
# # and colors. We have to set the clipping region on
# # the grid's DC, otherwise the text will spill over
# # to the next cell
#
# // right hand line
dc.SetPen( wx.Pen(wx.Colour( 255, 0, 0 ) , 1, wx.SOLID))
# //dc.SetBrush(wxBrush(wxColour(255, 255, 255), wxSOLID));
dc.DrawLine( rect.x + rect.width-1, rect.y, rect.x +
rect.width-1, rect.y + rect.height)
# left
dc.DrawLine( rect.x, rect.y, rect.x, rect.y + rect.height)
# top
dc.DrawLine( rect.x, rect.y, rect.x + rect.width, rect.y)
# bottom
dc.DrawLine( rect.x, rect.y + rect.height-1, rect.x +
rect.width, rect.y + rect.height-1 )
# --------------------------------------------------------------------
# Sample Grid using a specialized table and renderers that can
# be plugged in based on column names
class MegaGrid(Grid.Grid):
def __init__(self, parent, data, colnames):
"""parent, data, colnames, plugins=None
Initialize a grid using the data defined in data and colnames
(see MegaTable for a description of the data format)
plugins is a dictionary of columnName -> column renderers.
"""
# The base class must be initialized *first*
Grid.Grid.__init__(self, parent, -1)
self._table = MegaTable(data, colnames)
self.SetTable(self._table)
# damufo
# self.SetCellSize(1, 1, 2, 1)
print "getcellsize", self.GetCellSize(1, 1)
print "conbina"
# fin damufo
# damufo
# fin damufo
self.Bind(Grid.EVT_GRID_LABEL_RIGHT_CLICK,
self.OnLabelRightClicked)
def Reset(self):
"""reset the view based on the data in the table. Call
this when rows are added or destroyed"""
self._table.UpdateCellAttrs(self, 1,1)
self._table.UpdateCellAttrs(self, row=4,col=1)
self._table.ResetView(self)
self.SetDefaultCellAlignment( wx.ALIGN_LEFT, wx.ALIGN_CENTRE )
self.SetCellSize(1, 1, 2, 1)
self._table.SetValue(1, 1, "texto prueba")
self._table.SetValue(0, 0, "12")
def OnLabelRightClicked(self, evt):
# Did we click on a row or a column?
row, col = evt.GetRow(), evt.GetCol()
if row == -1: self.colPopup(col, evt)
elif col == -1: self.rowPopup(row, evt)
def rowPopup(self, row, evt):
"""(row, evt) -> display a popup menu when a row label is right
clicked"""
appendID = wx.NewId()
deleteID = wx.NewId()
x = self.GetRowSize(row)/2
if not self.GetSelectedRows():
self.SelectRow(row)
menu = wx.Menu()
xo, yo = evt.GetPosition()
menu.Append(appendID, "Append Row")
menu.Append(deleteID, "Delete Row(s)")
def append(event, self=self, row=row):
self._table.AppendRow(row)
self.Reset()
def delete(event, self=self, row=row):
rows = self.GetSelectedRows()
self._table.DeleteRows(rows)
self.Reset()
self.Bind(wx.EVT_MENU, append, id=appendID)
self.Bind(wx.EVT_MENU, delete, id=deleteID)
self.PopupMenu(menu)
menu.Destroy()
return
def colPopup(self, col, evt):
"""(col, evt) -> display a popup menu when a column label is
right clicked"""
x = self.GetColSize(col)/2
menu = wx.Menu()
id1 = wx.NewId()
sortID = wx.NewId()
xo, yo = evt.GetPosition()
self.SelectCol(col)
cols = self.GetSelectedCols()
self.Refresh()
menu.Append(id1, "Delete Col(s)")
menu.Append(sortID, "Sort Column")
def delete(event, self=self, col=col):
cols = self.GetSelectedCols()
self._table.DeleteCols(cols)
self.Reset()
def sort(event, self=self, col=col):
self._table.SortColumn(col)
self.Reset()
self.Bind(wx.EVT_MENU, delete, id=id1)
if len(cols) == 1:
self.Bind(wx.EVT_MENU, sort, id=sortID)
self.PopupMenu(menu)
menu.Destroy()
return
# -----------------------------------------------------------------
# Test data
# data is in the form
# [rowname, dictionary]
# where dictionary.get(colname, None) -> returns the value for the cell
#
# the colname must also be supplied
import random
colnames = ["Row", "This", "Is", "A", "Test", "B"]
data = []
for row in range(10):
d = {}
for name in ["This", "Test", "Is"]:
d[name] = random.random()
d["Row"] = len(data)
# XXX
# the "A" column can only be between one and 4
d["A"] = random.choice(range(4))
d["B"] = "Prueba"
data.append((str(row), d))
#---------------------------------------------------------------------------
class TestFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1,
"Test Frame", size=(640,480))
grid = MegaGrid(self, data, colnames)
grid.EnableGridLines( True )
grid.Reset()
self.Show(True)
overview = """Mega Grid Example
This example attempts to show many examples and tricks of
using a virtual grid object. Hopefully the source isn't too jumbled.
Features:
<ol>
<li>Uses a virtual grid
<li>Columns and rows have popup menus (right click on labels)
<li>Columns and rows can be deleted (i.e. table can be
resized)
<li>Dynamic renderers. Renderers are plugins based on
column header name. Shows a simple Font Renderer and
an Image Renderer.
</ol>
Look for 'XXX' in the code to indicate some workarounds for non-obvious
behavior and various hacks.
"""
if __name__ == '__main__':
import sys,os
# import run
app = wx.App(redirect=False) # Error messages go to popup window
name = os.path.basename(sys.argv[0])
frame = wx.Frame(None, -1, "RunDemo: " + name, pos=(50,50),
size=(200,100),
style=wx.DEFAULT_FRAME_STYLE, name="run a sample")
win = TestFrame(frame)
# win.Show(True)
app.MainLoop()
Más información sobre la lista de distribución Python-es