Calculating flow panel width based on its contents - delphi

I am dynamically populating frames into flow panels (as part of a horizontally oriented VCL Metropolis app). I need to resize each group's flow panel to fit all its items horizontally. I have a very simple formula which does the trick sometimes, but not all the time - specifically when adding an odd number of items. The flow panel's FlowStyle is set to fsTopBottomLeftRight and fits 2 frames vertically.
For example, adding 7 items automatically detects the correct width (4 items across). But adding 5 items does not detect the correct width (supposed to be 3 across but winds up detecting 2 across).
How can I make it correctly calculate the width for each group?
Here's the procedure that populates the items into each item group (some irrelevant stuff removed):
procedure TSplitForm.LoadScreen;
const
FRAME_WIDTH = 170; //Width of each frame
FRAME_HEIGHT = 250; //Height of each frame
FRAME_MARGIN = 30; //Margin to right of each group
FRAME_VERT_COUNT = 2; //Number of frames vertically stacked
var
CurGroup: TFlowPanel; //Flow panel currently being populated
procedure ResizeGroup(FP: TFlowPanel);
var
Count, CountHalf, NewWidth, I: Integer;
begin
//Resize the specific flow panel's width to fit all items
Count:= FP.ComponentCount;
NewWidth:= FRAME_WIDTH + FRAME_MARGIN; //Default width if no items
if Count > 0 then begin
//THIS IS WHERE MY CALCULATIONS DO NOT WORK
CountHalf:= Round(Count / FRAME_VERT_COUNT);
NewWidth:= (CountHalf * FRAME_WIDTH) + FRAME_MARGIN;
end;
if FP.Parent.Width <> NewWidth then
FP.Parent.Width:= NewWidth;
//Resize main flow panel's width to fit all contained group panels
//(automatically extends within scroll box to extend scrollbar)
Count:= TFlowPanel(FP.Parent.Parent).ControlCount;
NewWidth:= 0;
for I := 0 to Count-1 do begin
NewWidth:= NewWidth + FP.Parent.Parent.Controls[I].Width;
end;
NewWidth:= NewWidth + FRAME_MARGIN;
if FP.Parent.Parent.Width <> NewWidth then
FP.Parent.Parent.Width:= NewWidth;
end;
procedure Add(const Name, Title, Subtitle: String);
var
Frame: TfrmItemFrame;
begin
Frame:= AddItemFrame(CurGroup, Name); //Create panel, set parent and name
Frame.OnClick:= ItemClick;
Frame.Title:= Title;
Frame.Subtitle:= Subtitle;
ResizeGroup(CurGroup);
end;
begin
CurGroup:= fpMainGroup;
Add('boxMainItem1', 'Item 1', 'This is item 1');
Add('boxMainItem2', 'Item 2', 'This is item 2');
Add('boxMainItem3', 'Item 3', 'This is item 3');
Add('boxMainItem4', 'Item 4', 'This is item 4');
Add('boxMainItem5', 'Item 5', 'This is item 5');
CurGroup:= fpInventoryGroup;
Add('boxInventItem1', 'Item 1', 'This is item 1');
Add('boxInventItem2', 'Item 2', 'This is item 2');
Add('boxInventItem3', 'Item 3', 'This is item 3');
Add('boxInventItem4', 'Item 4', 'This is item 4');
Add('boxInventItem5', 'Item 5', 'This is item 5');
Add('boxInventItem6', 'Item 6', 'This is item 6');
Add('boxInventItem7', 'Item 7', 'This is item 7');
end;
This is a screenshot of what that code is producing:
As you can see, the first group with 5 items is hiding the 5th item, but the second group with 7 items is showing all 7 just fine.
The structure of parent/child relationships is like so (with flow panels in question bold):
SplitForm: TSplitForm (main form)
ScrollBox2: TScrollBox (container of main flow panel)
fpMain: TFlowPanel (container of all group panels)
pMainGroup: TPanel (container of flow panel and title panel)
fpMainGroup: TFlowPanel (container of item frames)
pMainGroupTitle: TPanel (title at top of group)
pInventoryGroup: TPanel (container of flow panel and title panel)
fpInventoryGroup: TFlowPanel (container of item frames)
pInventoryGroupTitle: TPanel (title at top of group)
(other panels for more groups)
I tried using each flow panel's AutoSize property, but it didn't acknowledge the heights (2 up) and made things even worse. I basically just need to properly detect the total number of columns within these flow panels.

Round(Count / FRAME_VERT_COUNT);
Here FRAME_VERT_COUNT is 2. When Count is 5 your expression becomes
Rount(2.5);
The default rounding mode is bankers rounding and this evaluates to 2. When Count is 7 the expression is
Round(3.5);
Bankers rounding means this is 4.
You could do what Sertac suggests and use ceil. However, I would simply avoid floating point altogether. It is just not needed and as a general rule, integer arithmetic is always to be preferred if it is viable. Your expression should be
(Count + FRAME_VERT_COUNT - 1) div FRAME_VERT_COUNT

You don't want a partial tile, so when you're calculating how many columns are needed you want the nearest (equal or greater) integer.
In the default rounding mode, Round(7/2) is '4'. That's fine. However Round(5/2) is '2'. That's because
With the default rounding mode (rmNearest), if X is exactly halfway
between two whole numbers, the result is always the even number.
With only two rows, rounding up can be a solution (division is always a whole number or a number exactly in between two whole numbers). For a general solution, better use Ceil.

Related

Firemonkey Listbox needs a TopItem

I need to be able to get and set the top item in a listbox - something like a ListBox.TopItem property would be great. I have been unable to find anything that does this job. Any ideas would be greatly appreciated please.
Edit:
For example:
Listbox1 and ListBox2 items are the following:
1 Data1
2 Data2
3 More Data
4 More again
5 Yet more
6 and this will do.
Showing in 2 listboxes, both 3 items high:
1 Data1
2 Data2
3 More Data
and I want to programmatically make them show
3 More Data
4 More again
5 Yet more
and I want to find out what item the top one is.
(previous answer text deleted)
Update after clarification of question.
Ok, so you want
a) to scroll the list programmatically
b) to read the topmost item programmatically
The following scrolls the list so that a given item becomes the top visible item. Note however, that the list can not be scrolled up beyond the point that there would be empty space between the last item and the viewport's bottom.
procedure TForm25.SetTopVisibleItem(idx: integer);
var
ptf: TPointF;
begin
ptf := PointF(0, idx * ListBox1.ItemHeight);
ListBox1.ViewportPosition := ptf;
end;
To get the current topmost item in the viewport:
function TForm25.GetTopVisibleItem: TListBoxItem;
var
x, y: single;
begin
x := 3; // a small offset is required to assure that
y := 3; // the point is within an item
result := ListBox1.ItemByPoint(x, y);
end;

TStringGrid: Why OnClick after OnKeyDown

Why does a Delphi StringGrid sometimes calls the OnClick event after an OnKeyDown?
Debugging screenshot:
My OnKeyDown event handler:
var
Top: Integer;
Bottom: Integer;
CurrentRow: Integer;
begin
Top := Grid.TopRow;
Bottom := Grid.TopRow + Grid.VisibleRowCount - 1;
if (Key = 38) then CurrentRow := Grid.Row - 1
else if (Key = 40) then CurrentRow := Grid.Row + 1;
// Disable OnClick because sometimes a 'TStringGrid.Click' is called anyway...
// (when clicking on form top window bar and navigating)
Grid.OnClick := nil;
if (CurrentRow < Top - 1) or (CurrentRow > Bottom + 1) then begin
if (Key = 38) then Grid.Row := Bottom
else if (Key = 40) then Grid.Row := Top;
end;
Grid.OnClick := GridClick;
end;
Edit:
It seems the 'OnClick' is not being fired when the last line is selected and pushing 'Down' or when the first line is selected and pushing 'Up'.
Way to reproduce:
Add a TStringGrid to a form and populate with a few lines. Add 'OnClick' and 'OnKeyDown' handler. No specific code needs to be added in these two handler methods. Select a row in the stringgrid on the form and press the up or down arrow on your keyboard.
Edit 2:
This isn't the solution, but to prevent the code in 'OnClick' being executed after pressing up, down, pageup or pagedown, I set a variable in 'OnKeyDown' what key was pressed and check for that variable in 'OnClick'.
Edit 3:
Updated stack trace and way to reproduce.
Well, that hard-coded key codes aren't the case making the least bit transparent, but you witness this effect when you use a direction key (up, down, left, etc...) to change the selection.
Why the OnClick event handler is called, is because TCustomGrid.OnKeyDown calls TCustomGrid.FocusCell, which calls Click.
Exactly why changing focus to another cell would establish a click I do not know, we would have to ask the developers I imagine. Perhaps to simulate the default behaviour when changing focus to another cell by clicking instead of keyboard.
Since you seem to handle direction key presses yourself, maybe you could consider to prevent this from happening at all by ignoring the key any further:
if Key in [VK_PRIOR..VK_DOWN] then
Key := 0;

List view control drawn incorrectly when groups are present

I was experimenting with list view groups, and it turns out the control displays incorrectly when the application starts.
As soon as I resize the form it displays correctly:
I do not understand what is happening. Can anyone explain?
It's a bug in the Delphi control which I have reproduced. I'm not sure yet what causes the bug. I have submitted this to Quality Central as QC#101104.
I found a simple workaround by adding the following code to the form's OnShow event.
ListView1.Align := alNone;
ListView1.Align := alClient;
The following DFM file is enough to demonstrate the problem:
object MyForm: TMyForm
Left = 0
Top = 0
ClientHeight = 300
ClientWidth = 635
object ListView1: TListView
Left = 200
Top = 96
Width = 250
Height = 150
Align = alClient
Columns = <
item
Caption = 'Column'
end>
Groups = <
item
Header = 'Group header'
GroupID = 0
end>
Items.ItemData = {
052A0000000100000000000000FFFFFFFFFFFFFFFF0000000000000000000000
000854006800650020006900740065006D00}
GroupView = True
ViewStyle = vsReport
end
end
It turns out that another way to resolve the problem is to move the ViewStyle entry in the DFM file so that it appears before the Items entry. So yet another workaround for the problem would be to add the items at runtime. In fact this probably explains why this bug has not been found since I bet that the overwhelming majority of list view code adds the items at runtime.

Delphi: How to draw some text in requested width and number of lines, with ending ellipsis?

I need to draw some text in a table cell with fixed width (in pixels) and fixed number of text lines. If the text is clipped by cell rectangle, it must end with ellipsis. The problem is I can't calculate the text rectangle correctly (or the TextRect/DrawText procedure isn't working correctly, I'm not sure).
I tried to use this method of calculating text rectangle:
var
TextRect: TRect;
tm: TEXTMETRIC;
...
GetTextMetrics(Canvas.Handle, tm);
TextLineHeight := tm.tmHeight + tm.tmExternalLeading;
TextRect.Bottom := TextRect.Top + TextLineHeight * NumberOfLines;
Canvas.TextRect(TextRect, 'some long long long text',
[tfTop, tfLeft, tfEndEllipsis, tfWordBreak]);
The clipping rectangle has been calculated correctly, but the ellipsis isn't appearing.
Ellipsis appearing when I decrease the height of clipping rectangle by 1 pixel:
TextRect.Bottom := TextRect.Top + TextLineHeight * NumberOfLines - 1;
But some pixels of the bottom line of my text are clipped then.
How to do it correctly?
Since the api puts the end-ellipsis only when the last line does not fit in the specified rectangle, one workaround could be to specify tfModifyStringin formatting options in a first call to 'TextRect' with a rectangle with reduced height, then call 'TextRect' again with a proper sized rectangle and the modified text:
var
Text: string;
...
Text := 'some long long long text';
SetLength(Text, Length(Text) + 4); // as per DrawTextEx documentation
Dec(TextRect.Bottom);
Canvas.TextRect(TextRect, Text,
[tfTop, tfLeft, tfEndEllipsis, tfWordBreak, tfModifyString]);
Inc(TextRect.Bottom);
Canvas.TextRect(TextRect, Text, [tfTop, tfLeft, tfWordBreak]);
I'd be keeping an eye though, in case a future version of the OS decides to clip the last line entirely if it doesn't entirely fit in the rectangle.. :)
I'd try calculating the needed rectangle via Canvas.TextRect(..., [tfCalcRect, ...]).

Virtual StringTree: How to determine if the node text is completely shown?

When TVirtualStreeTree.HintMode = hmTooltip, the node text will become the hint text when the mouse is hovered over a node and column where the node text is not completely shown. But I have to set HintMode = hmHint, so that I can in the even handler supply various hint text based on the position the current mouse cursor is, and in that HintMode the hint text is not generated automatically.
My question is how to know if the a node text is shown completely or not, so that I know should I supply the node text or empty string as the hint text?
Thanks.
You can call TBaseVirtualTree.GetDisplayRect to determine the text bounds of a node. Depending on the Unclipped parameter, it will give you the full or actual text width. TextOnly should be set to True:
function IsTreeTextClipped(Tree: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex): Boolean;
var
FullRect, ClippedRect: TRect;
begin
FullRect := Tree.GetDisplayRect(Node, Column, True, True);
ClippedRect := Tree.GetDisplayRect(Node, Column, True, False);
Result := (ClippedRect.Right - ClippedRect.Left) < (FullRect.Right - FullRect.Left);
end;
Note that the function will implicitly initialize the node if it's not been initialized yet.
You can use what the tree control itself uses. Here's an excerpt from the cm_HintShow message handler for single-line nodes when hmTooltip mode is in effect.
NodeRect := GetDisplayRect(HitInfo.HitNode, HitInfo.HitColumn, True, True, True);
BottomRightCellContentMargin := DoGetCellContentMargin(HitInfo.HitNode, HitInfo.HitColumn
, ccmtBottomRightOnly);
ShowOwnHint := (HitInfo.HitColumn > InvalidColumn) and PtInRect(NodeRect, CursorPos) and
(CursorPos.X <= ColRight) and (CursorPos.X >= ColLeft) and
(
// Show hint also if the node text is partially out of the client area.
// "ColRight - 1", since the right column border is not part of this cell.
( (NodeRect.Right + BottomRightCellContentMargin.X) > Min(ColRight - 1, ClientWidth) ) or
(NodeRect.Left < Max(ColLeft, 0)) or
( (NodeRect.Bottom + BottomRightCellContentMargin.Y) > ClientHeight ) or
(NodeRect.Top < 0)
);
If ShowOwnHint is true, then you should return the node's text as the hint text. Otherwise, leave the hint text blank.
The main obstacle with using that code is that DoGetCellContentMargin is protected, so you can't call it directly. You can either edit the source to make it public, or you can duplicate its functionality in your own function; if you aren't handling the OnBeforeCellPaint event, then it always returns (0, 0) anyway.
The HitInfo data comes from calling GetHitTestInfoAt.

Resources