2010-08-22 40 views

Respuesta

15

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; 
+0

Gracias. Entonces, si quiero que se centre a medida que el usuario escribe en sus celdas, entonces debería hacer esto en onEdit()? – Mahm00d

+0

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

+0

Flom, he actualizado la respuesta. –

1

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

3

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

+0

hmm ... ¿cuál de los dos sobrantes es el correcto? – kleopatra

1

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.

Cuestiones relacionadas