Parece algo obvio tener. Quiero que los textos estén en el centro de las celdas, pero por alguna razón no puedo encontrarlos en las propiedades. ¿Cómo puedo hacer esto?Delphi: ¿Cómo hacer que los textos de las celdas en el centro de TStringGrid estén alineados?
Respuesta
No hay propiedad para centrar el texto en TStringGrid, pero se puede hacer que en caso DrawCell como:
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
S: string;
SavedAlign: word;
begin
if ACol = 1 then begin // ACol is zero based
S := StringGrid1.Cells[ACol, ARow]; // cell contents
SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER);
StringGrid1.Canvas.TextRect(Rect,
Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S);
SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign);
end;
end;
El código que he publicado desde here
ACTUALIZACIÓN:
a centro de texto mientras escribe en la celda, agregue este código al GetEditText
Evento:
procedure TForm1.StringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer;
var Value: string);
var
S : String;
I: Integer;
IE : TInplaceEdit ;
begin
for I := 0 to StringGrid1.ControlCount - 1 do
if StringGrid1.Controls[i].ClassName = 'TInplaceEdit' then
begin
IE := TInplaceEdit(StringGrid1.Controls[i]);
ie.Alignment := taCenter
end;
end;
En Delphi lo hago por la sobrecarga de tipo TEdit, de esta manera:
En la sección de interfaz, antes de cualquier declaración TForm puse:
type TStringGrid=class(Grids.TStringGrid)
private
FCellsAlignment:TStringList;
function GetCellsAlignment(ACol,ARow:Integer):TAlignment;
procedure SetCellsAlignment(ACol,ARow:Integer;const Alignment:TAlignment);
protected
procedure DrawCell(ACol,ARow:Longint;ARect:TRect;AState:TGridDrawState);override;
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
property CellsAlignment[ACol,ARow:Integer]:TAlignment read GetCellsAlignment write SetCellsAlignment;
end;
En la sección de implementación pongo la aplicación de tales :
constructor TStringGrid.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FCellsAlignment:=TStringList.Create;
FCellsAlignment.CaseSensitive:=True;
FCellsAlignment.Sorted:=True;
FCellsAlignment.Duplicates:=dupIgnore;
end;
destructor TStringGrid.Destroy;
begin
FCellsAlignment.Free;
inherited Destroy;
end;
procedure TStringGrid.SetCellsAlignment(ACol,ARow:Integer;const Alignment:TAlignment);
begin
FCellsAlignment.AddObject(IntToStr(ACol)+'-'+IntToStr(ARow),TObject(Alignment));
end;
function TStringGrid.GetCellsAlignment(ACol,ARow:Integer):TAlignment;
var
Index:Integer;
begin
Index:=FCellsAlignment.IndexOf(IntToStr(ACol)+'-'+IntToStr(ARow));
if -1<Index
then begin
GetCellsAlignment:=TAlignment(FCellsAlignment.Objects[Index]);
end
else begin
GetCellsAlignment:=taLeftJustify;
end;
end;
procedure TStringGrid.DrawCell(ACol,ARow:Longint;ARect:TRect;AState:TGridDrawState);
var
Old_DefaultDrawing:Boolean;
begin
if DefaultDrawing
then begin
case CellsAlignment[ACol,ARow]
of
taLeftJustify
:begin
Canvas.TextRect(ARect,ARect.Left+2,ARect.Top+2,Cells[ACol,ARow]);
end;
taRightJustify
:begin
Canvas.TextRect(ARect,ARect.Right-2-Canvas.TextWidth(Cells[ACol,ARow]),ARect.Top+2,Cells[ACol,ARow]);
end;
taCenter
:begin
Canvas.TextRect(ARect,(ARect.Left+ARect.Right-Canvas.TextWidth(Cells[ACol,ARow]))div 2,ARect.Top+2,Cells[ACol,ARow]);
end;
end;
end;
Old_DefaultDrawing:=DefaultDrawing;
DefaultDrawing:=False;
inherited DrawCell(ACol,ARow,ARect,AState);
DefaultDrawing:=Old_DefaultDrawing;
end;
continuación para ajustar la alineación de celdas i poner algo como esto:
CellsAlignment[TheCellCol,TheCellRow]:=taLeftJustify;
CellsAlignment[TheCellCol,TheCellRow]:=taCenter;
CellsAlignment[TheCellCol,TheCellRow]:=taRightJustify;
Eso es todo.
Pelase, nota que se puede mejorar mucho, es solo una prueba de concepto de agregarlo a TStingGrid, no se trata de crear una nueva clase (con otro nombre) y tampoco se trata de crear un nuevo componente .
Espero que esto puede ser útil para alguien.
PD: La misma idea se puede hacer por TEdit, simplemente buscar en stackoverflow.com para TEdit.CreateParams
o leer correos How to set textalignment in TEdit control
Nota: Ya que no puedo borrar mensajes (si un administrador puede hacer por favor bórrelos y elimine este párrafo), intento editarlos para que solo este sea. Esta es una solución mucho mejor que las otras y en ellas hubo un error en los procedimientos TStringGrid.SetCellsAlignment
y TStringGrid.SetCellsAlignment
la comparación -1<Index
fue correcta, pero then
y else
partes se intercambian ... La versión correcta (esta) mostrará que cuando se indexa es más grande que -1 sobrescribirá el valor almacenado, de lo contrario agregará una nueva entrada, los demás harán lo contrario sacando una lista del mensaje índice, gracias por detectarlo.
También he hacer capaz de ser todo en otra unidad separada, así que aquí está (esperanza ahora es correcta y gracias por la detección de tales mistypes):
unit AlignedTStringGrid;
interface
uses Windows,SysUtils,Classes,Grids;
type TStringGrid=class(Grids.TStringGrid)
private
FCellsAlignment:TStringList;
FColsDefaultAlignment:TStringList;
function GetCellsAlignment(ACol,ARow:Integer):TAlignment;
procedure SetCellsAlignment(ACol,ARow:Integer;const Alignment:TAlignment);
function GetColsDefaultAlignment(ACol:Integer):TAlignment;
procedure SetColsDefaultAlignment(ACol:Integer;const Alignment:TAlignment);
protected
procedure DrawCell(ACol,ARow:Longint;ARect:TRect;AState:TGridDrawState);override;
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
property CellsAlignment[ACol,ARow:Integer]:TAlignment read GetCellsAlignment write SetCellsAlignment;
property ColsDefaultAlignment[ACol:Integer]:TAlignment read GetColsDefaultAlignment write SetColsDefaultAlignment;
end;
implementation
constructor TStringGrid.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FCellsAlignment:=TStringList.Create;
FCellsAlignment.CaseSensitive:=True;
FCellsAlignment.Sorted:=True;
FCellsAlignment.Duplicates:=dupIgnore;
FColsDefaultAlignment:=TStringList.Create;
FColsDefaultAlignment.CaseSensitive:=True;
FColsDefaultAlignment.Sorted:=True;
FColsDefaultAlignment.Duplicates:=dupIgnore;
end;
destructor TStringGrid.Destroy;
begin
FCellsAlignment.Free;
FColsDefaultAlignment.Free;
inherited Destroy;
end;
procedure TStringGrid.SetCellsAlignment(ACol,ARow:Integer;const Alignment:TAlignment);
var
Index:Integer;
begin
if -1<Index
then begin
FCellsAlignment.Objects[Index]:=TObject(Alignment);
end
else begin
FCellsAlignment.AddObject(IntToStr(ACol)+'-'+IntToStr(ARow),TObject(Alignment));
end;
end;
function TStringGrid.GetCellsAlignment(ACol,ARow:Integer):TAlignment;
var
Index:Integer;
begin
Index:=FCellsAlignment.IndexOf(IntToStr(ACol)+'-'+IntToStr(ARow));
if -1<Index
then begin
GetCellsAlignment:=TAlignment(FCellsAlignment.Objects[Index]);
end
else begin
GetCellsAlignment:=ColsDefaultAlignment[ACol];
end;
end;
procedure TStringGrid.SetColsDefaultAlignment(ACol:Integer;const Alignment:TAlignment);
var
Index:Integer;
begin
Index:=FColsDefaultAlignment.IndexOf(IntToStr(ACol));
if -1<Index
then begin
FColsDefaultAlignment.Objects[Index]:=TObject(Alignment);
end
else begin
FColsDefaultAlignment.AddObject(IntToStr(ACol),TObject(Alignment));
end;
end;
function TStringGrid.GetColsDefaultAlignment(ACol:Integer):TAlignment;
var
Index:Integer;
begin
Index:=FColsDefaultAlignment.IndexOf(IntToStr(ACol));
if -1<Index
then begin
GetColsDefaultAlignment:=TAlignment(FColsDefaultAlignment.Objects[Index]);
end
else begin
GetColsDefaultAlignment:=taLeftJustify;
end;
end;
procedure TStringGrid.DrawCell(ACol,ARow:Longint;ARect:TRect;AState:TGridDrawState);
var
Old_DefaultDrawing:Boolean;
begin
if DefaultDrawing
then begin
case CellsAlignment[ACol,ARow]
of
taLeftJustify
:begin
Canvas.TextRect(ARect,ARect.Left+2,ARect.Top+2,Cells[ACol,ARow]);
end;
taRightJustify
:begin
Canvas.TextRect(ARect,ARect.Right-2-Canvas.TextWidth(Cells[ACol,ARow]),ARect.Top+2,Cells[ACol,ARow]);
end;
taCenter
:begin
Canvas.TextRect(ARect,(ARect.Left+ARect.Right-Canvas.TextWidth(Cells[ACol,ARow]))div 2,ARect.Top+2,Cells[ACol,ARow]);
end;
end;
end;
Old_DefaultDrawing:=DefaultDrawing;
DefaultDrawing:=False;
inherited DrawCell(ACol,ARow,ARect,AState);
DefaultDrawing:=Old_DefaultDrawing;
end;
end.
Esta es una unidad completa, guardarlo a un archivo llamado AlignedTStringGrid.pas
.
Luego en cualquier forma tiene TStringGrid
agregue ,AlignedTStringGrid
al final de la interfaz usa cláusula.
Nota: Lo mismo se puede hacer para las filas, pero por ahora no sé cómo mezclar ambas (columnas y filas) debido a cómo seleccionar la prioridad, si alguien está muy interesado en él, hágamelo saber.
P.D. .: La misma idea se puede hacer por TEdit, simplemente buscar en stackoverflow.com para TEdit.CreateParams
o leer correos How to set textalignment in TEdit control
hmm ... ¿cuál de los dos sobrantes es el correcto? – kleopatra
En Lázaro se puede crear a partir inspector de objetos. Encuentra columnas de propiedades en TStringGrid que creaste y agrega algunos elementos. A continuación, expanda su TStringGrid en el Explorador de objetos, seleccione la cuadrícula que desea alinear y modifique su propiedad Alineación.
- 1. ¿Cómo puede obtener pistas para que las celdas en una TStringGrid aparezcan de forma más fluida?
- 2. ¿Cómo hacer que las variables estén disponibles en la plantilla?
- 3. Cómo pinto el fondo de TStringGrid
- 4. ¿Cómo hacer que todos los caracteres estén minúsculos en NSString?
- 5. ¿Cómo hacer que las funciones $ (documento) .ready() estén disponibles globalmente?
- 6. Cómo alinear los componentes JSF al centro
- 7. Cómo hacer que TextView tenga el mismo tamaño independientemente de los textos dentro de
- 8. Atlassian JIRA Plugin Development: cómo hacer que las variables estén disponibles para las plantillas de velocidad
- 9. ¿Cómo hacer que las celdas sean de solo lectura en las hojas de cálculo?
- 10. ¿Cómo centrar los contenidos de las celdas de una tabla LaTeX cuyas columnas tienen anchos fijos?
- 11. Cómo deshabilitar los puntos suspensivos de los textos de celda en WindowsForms DataGridView?
- 12. delphi: mover entre las celdas de la cuadrícula
- 13. ¿Cómo obtengo los conteos para seleccionar todas las celdas que no están en blanco en Excel?
- 14. hacer que las variables estén disponibles fuera de la función en PHP?
- 15. Opciones de Django para hacer que las variables estén ampliamente disponibles
- 16. ¿Cuál es la mejor manera de hacer que las bibliotecas compartidas estén disponibles para múltiples aplicaciones?
- 17. ¿Cómo puedo verificar que las páginas web estén comprimidas?
- 18. Delphi - Dibujar texto multilínea en el centro de una rect
- 19. jqGrid: cómo cambiar el relleno de celdas
- 20. Extraiga los nombres de los textos (Java)
- 21. TextBlock.TextWrapping: cómo hacer que el texto se ajuste para que las líneas se alineen en el centro?
- 22. ¿Alguien ha intentado hacer que las funciones del sistema de PHP estén más orientadas a objetos?
- 23. ¿Alguna manera de reducir el tamaño de los textos?
- 24. ¿Cómo hacer marcos de Delphi en C#?
- 25. Alinea los valores de las celdas en JTable?
- 26. Cómo desplazar un TStringGrid dinámicamente?
- 27. centro documentView en el centro de NSScrollView
- 28. ¿Cómo hacer que las secuencias de BLOB estén disponibles en objetos viejos sin formato C# cuando se usa SqlDataReader?
- 29. DataGridView: ¿Cómo hacer que algunas celdas sean no seleccionables?
- 30. FillRect no pinta la celda completa de TStringGrid en Delphi XE2
Gracias. Entonces, si quiero que se centre a medida que el usuario escribe en sus celdas, entonces debería hacer esto en onEdit()? – Mahm00d
El código anterior se implementa en el evento 'OnDrawCell' y se debe dejar allí. Si desea que la entrada se centre como la del centro del usuario, debe usar los eventos de pintura de los editores TEdit/TWhateverEdit para eso. – zz1433
Flom, he actualizado la respuesta. –