Dynamically setting col width in string grid

I am trying to set the width of the columns in a string grid depending on the width of the data.

I can calculate the maximum number of chraracters used in any column. My questions are:-


1) if I use non proportional fonts how do I convert from font size to pitch in pixels?
2) if I use proportional spaced fonts how do I get the length of the actual text in pixells?

Thanks in anticipation


Alan
LVL 1
alanjbrownAsked:
Who is Participating?
 
shaneholmesCommented:
Here is an example using TextWidth.
This example iterates through the grid adjusting the colwidths

Shane

var
  i, j, ColWidth, ThisCelllWidth : integer;
begin
with StringGrid1 do
  begin
    For j := 0 to (ColCount - 1) do begin
      ColWidth := 0;
      For i := 0 to (RowCount -1) do begin
        ThisCellWidth := StringGrid1.Canvas.TextWidth(Cells[j,i])
        If ThisCellWidth > ColWidth then ColWidth := ThisCellWidth;
      end; {for all rows}
      StringGrid1.ColWidths[j] := ColWidth + 2; {or + whatever margin you want}
  end; {for all columns}
end; {with StringGrid1}

Shane
0
 
mokuleCommented:
Canvas.TextWidth(str1) in both cases
0
 
KristianCommented:
You will need to set the font first mokule.

use:

canvas.font.name := 'fontnamehere';
canvas.font.size := 14;
etc
then :
Canvas.TextWidth(str1)

Kristian
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
mokuleCommented:
No Kristian, u don't need, but u can
0
 
shaneholmesCommented:
mokule is right, there is no need to reset the fonts. They should already be set before the call to TextWidth, however, you can change them to something else, if you'd like, just before getting the width.

Shane
0
 
KristianCommented:
just a force of habit,
our grids have different fonts in cells to titles, so i always set the font just as habit really to be sure.
K
0
 
alanjbrownAuthor Commented:
Thank you all for the help
0
 
mokuleCommented:
Hi alanjbrown
Could You please answer what was wrong in my answer to You question.
Kind regards
Marek
0
 
alanjbrownAuthor Commented:
Hi Marek

There was nothing wrong with your answer, however when I looked at all the answers received, Shane's answer was the most complete. I therefore decided to award him the points.

Regards
Alan
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.