Change checkbox without firing OnChange in firemonkey - firemonkey

There are various tricks in the VCL world to set a checkbox state with out triggering a change event, for example:
yourCheckBox.Perform(BM_SETCHECK, 1, 0)
Or less elegantly removing the event, change the state and restoring the event.
My question is, are there any recognized methods to change the state of a checkbox in firemonkey without causing an OnChange event?

I discovered this answer (Change CheckBox state without calling OnClick Event) that uses helper classes to implement the feature. This is VCL and Firemonkey friendly with the caveat that one can only have one helper class per class. This means if someone else also has a helper class for TCheckbox then only one of the helper classes will be used. The alternative method and one that avoids the helper class issue (pity) is to write a separate method such as:
procedure TfrmMain.setCheckBox (chkBox : TCheckBox; state : boolean);
var OnChangeHandler : TNotifyEvent;
begin
OnChangeHandler := chkBox.OnChange;
chkBox.OnChange := nil;
chkBox.IsChecked := state;
chkBox.OnChange := OnChangeHandler;
end;

Related

How to use Image1.Bitmap.BitmapChanged;

Bitmap.BitmapChanged; is protected in FMX.Graphics so I cannot use the procedure.
Useing a TImage or TImageControler I am drawing a line but the line does not show.
I am using this snippet:
imgc1.Bitmap.Canvas.BeginScene;
imgc1.Bitmap.Canvas.DrawLine(FStartPoint,FEndPoint, 100);
imgc1.Bitmap.Canvas.EndScene;
imgc1.Bitmap.BitmapChanged; // the original example said that this would redraw the image. In my CE Rio IDE the BitmapChanged is undefind. How can I use it?
Draw the line. IDE cannot find BitmapChanged.
BitmapChanged is a protected member. I need to write some code to handle the OnBitmapChanged event.
I understand now. Almost 30 years of developing in Delphi and this is the first time I have run into protected members. The examples I was using must not have been compiled else the writer would have had the same error that I had.
TBitmap.BitmapChanged() is a virtual method that simply fires the public TBitmap.OnChange event. Since it is protected, you can use an accessor class to reach it:
type
TBitmapAccess = class(TBitmap)
end;
TBitmapAccess(imgc1.Bitmap).BitmapChanged;
However, this is not really needed. TImage assigns its own internal OnChange event handler to its Bitmap. So it should react to changes to the Bitmap automatically. But, if for some reason it does not, the correct way to refresh the TImage is to call its Repaint() method:
imgc1.Repaint;
Which is exactly what TImage's internal OnChange handler does:
constructor TImage.Create(AOwner: TComponent);
begin
inherited;
FBitmap := TBitmap.Create(0, 0);
FBitmap.OnChange := DoBitmapChanged;
...
end;
procedure TImage.DoBitmapChanged(Sender: TObject);
begin
Repaint;
UpdateEffects;
end;

How do I pass a message from an object to another object in Free Pascal

I have a form and then I have a 'TPageControl' object (named 'MyPages') and a 'TButton' object (named 'MyButton') placed on it at design time.
Then I have a new class called 'TTab' which extends 'TTabSheet'. 'TTab' class has a 'TButton' object as one of its member variables like below.
class TTab = class(TTabSheet)
private
m_btnCloseTab: TButton;
end;
When I click on the 'MyButton', it would create a new 'TTab' object, init the tab (like instantiating the 'm_btnCloseTab') and add it to 'MyPages' at run time.
Procedure TForm1.MyButtonClick(Sender:TObject);
var
newTab: TTab;
newCaption: AnsiString;
begin
newCaption:= 'Tab' + IntToStr(count); //count is a global var
inc(count);
newTab:= TTab.Create(nil);
newTab.Init(newCaption);
newTab.Parent(MyPages);
end;
This is what the TTab.Init(newCaption: AnsiString) Procedure looks like.
Procedure TTab.Init(newCaption: AnsiString);
begin
Self.Caption:= newCaption;
m_btnCloseTab:= TButton.Create(nil);
with m_btnCloseTab do begin
Parent:= Self;
Left:= 10;
Top:= 10;
Caption:= 'Close Tab';
Visible:= True;
OnClick:= #closeTab;
end;
end;
That adds a new tab alright. The close button is also shown on each tab.
How do I click on the 'm_btnCloseTab' on each tab to close that particular tab?
If I define a destructor (by overriding the destructor of the TTabSheet) for TTab like below, I can call it from outside.
Destructor TTab.Destroy;
begin
if m_btnCloseTab <> nil then begin
m_btnCloseTab.Destroy;
m_btnCloseTab:= nil;
end;
inherited;
end;
But I cannot call the Destructor from inside the tab (well, you can). If I do it, I cannot free the m_btnCloseTab object as it would give an exception, because we are still its event handler. If I don't free it, the tab gets closed fine, but the memory gets leaked (because we did not free m_btnCloseTab).
I believe I have to trigger an event so that the destructor can be called from the outside of 'TTab'. I don't know how to do it.
Any help would be appreciated.
Thanks.
You can find Notification methods all over the LCL sources (and in Delphi as well, of course). A simple example is a TLabeledEdit: this is some kind of "TEdit" which contains a TLabel. If the Label is destroyed the LabeledEdit is notified of this because it must set the reference to the label to nil. Otherwise the destructor of TLabeledEdit would attempt to destroy the label again - BOOM. Here the method is like this (pasted from ExtCtrls):
procedure TCustomLabeledEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FEditLabel) and (Operation = opRemove) then
FEditLabel := nil;
end;
And here you can see what you have to do in your case:
procedure TTab.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = m_BtnCloseTab) and (Operation = opRemove) then
m_BtnCloseTab := nil;
end;
Please note that Notification is a virtual method and must be declared with the attribute "override" in the protected section of the component.
I would use a single button for this task.
Take m_btnCloseTab declaration out of TTab and put it in private main form.
Then on your main form's FormCreate:
m_btnCloseTab := TButton.Create( MyPages );
(the above assumes MyPages is a component placed on the form, if not it must be created first.)
Give the button a top and left that makes sense for your TTab's.
Now m_btnCloseTab will be freed when MyPages is freed which is freed when the form is closed.
Now all you have to do is create your new tabs as you like and when one is focused simply make that tab the parent of your button. You could do this, for instance, in the MyPages OnChange method or whatever it has like that.
When the button is clicked it does something like TTab( Parent ).Free;
However, you may need to store Parent in a local variable in the button's OnClick, say:
TempTab: TTab
Then simply set TempTab := TTab( Parent ), set Button's Parent to nil, then call TempTab.Free;
I would also give your Tabs an owner. That way if the user closes the form with tabs still open (that is, your button hasn't been clicked) the owner will free them.
So declare your tabs like:
newTab:= TTab.Create( MyPages );
This should solve all your problems and, after a bit of fiddling, is quite easy to manage.
One final recommendation I would use the method .Free and/or FreeAndNil( ) rather than calling .destroy directly.

Firemonkey use StylesData to set property of array object in style

I try to set the property of an object when filling a ListBox with ListBoxItems. The object is an ellipse added to the style used by the ListBox. The line of code below raises an exception:
ListBoxItem.StylesData['ellipsestyle.fill.Gradient.Points.Points[0].Color'] := newAlphaColor;
As a workaround, I tried to reach the property by getting the ellipsestyle object with ListBoxItem.FindStyleRessource, but the function returns nil.
Thank you !
StylesData can`t provide access to 'complex' properties.
you can do next workaround:
var
Obj: TObject;
myListBoxItem: TListBoxItem;
begin
// create new item
myListBoxItem:=TListBoxItem.Create(nil);
ListBox1.AddObject(myListBoxItem);
myListBoxItem.StyleLookup:='listboxitembottomdetail';
myListBoxItem.StylesData['ellipsestyle.fill.Kind']:=TValue.From<TBrushKind>(TBrushKind.Gradient);
// access to GradientPoints collection
Obj:=myListBoxItem.StylesData['ellipsestyle.fill.Gradient.Points'].AsObject;
if not (Obj is TGradientPoints) then
Exit;
TGradientPoints(Obj).Points[0].Color:=TAlphaColorRec.Blanchedalmond;
TGradientPoints(Obj).Points[1].Color:=TAlphaColorRec.Alpha;
About FindStyleResource:
First place, where you can get access to style object - OnApplyStyleLookup event of specified ListBoxItem. Before OnApplyStyleLookup (for example - immediatelly after creating Listboxitem) you cannot get access to style.
So, move your code to ListBoxItem.OnApplyStyleLookup and change it like this:
procedure TForm2.ListBoxItem1ApplyStyleLookup(Sender: TObject);
var
FMXObj: TFmxObject;
Ellipse: TEllipse;
begin
if not (Sender is TFmxObject) then
Exit;
FMXObj:=TFMXObject(Sender).FindStyleResource('ellipsestyle');// get object by it`s "StyleName".
if not (FMXObj is TEllipse) then
Exit;
Ellipse:=TEllipse(FMXObj);
Ellipse.Fill.Kind:=TBrushKind.Gradient;
Ellipse.Fill.Gradient.Points.Points[0].Color:=TAlphaColorRec.Blueviolet;
Ellipse.Fill.Gradient.Points.Points[1].Color:=TAlphaColorRec.Greenyellow;
end;
Also, you can force load style (this is not recommended way - by default, style for object loaded at the time of first painting):
var
FMXObj: TFmxObject;
Ellipse: TEllipse;
myListBoxItem: TListBoxItem;
begin
myListBoxItem:=TListBoxItem.Create(nil);
ListBox1.AddObject(myListBoxItem);
myListBoxItem.StyleLookup:='listboxitembottomdetail';
// force load style
myListBoxItem.NeedStyleLookup;
myListBoxItem.ApplyStyleLookup; // this method also call OnApplyStyleLookup event
FMXObj:=myListBoxItem.FindStyleResource('ellipsestyle');
if not (FMXObj is TEllipse) then
Exit;
Ellipse:=TEllipse(FMXObj);
Ellipse.Fill.Kind:=TBrushKind.Gradient;
Ellipse.Fill.Gradient.Points.Points[0].Color:=TAlphaColorRec.Blanchedalmond;
Ellipse.Fill.Gradient.Points.Points[1].Color:=TAlphaColorRec.Alpha;

Create an NSView in an event and return it through a parameter

I'd like to create an NSView derivative in an event and return it to the calling procedure. something like
...
if assigned(FMyEvent) then
FMyEvent(newview)
..
and the event would be assigned something like
procedure TForm6.AssignView(var view: Pointer);
begin
view := Pointer(TNSButton.Wrap(TNSButton.Wrap(TNSButton.OCClass.alloc).initWithFrame(MakeNSRect(200,0,100,50))));
end;
which will return an NSButton in this case.
Now because I want the event to be published I can't use an NSView as a parameter - because NSView is an OSX only definition and the form designer needs to know about the event in Windows as well. So I made it a Pointer type - but this crashes, it looks like a reference counter problem looking at the stack trace.
Could anyone suggest an alternative? or maybe I have to do something to increment the reference count? or if any one can point to some documentation on the delphi/osx interface that would be great.
Update:
I Cheated and just made a container - like this
TNSViewContainer = class
{$IFDEF MACOS}
private
FView: NSView;
procedure SetView(const Value: NSView);
published
property View : NSView read FView write SetView;
{$ENDIF}
end;
and I just pass one of these around - works a treat.

Is there a way to break out of event recursion in jQuery without using a global variable?

I have a form with 2 text inputs and 2 span controls. Normally, when textbox A is changed an event is fired to change span A, and when textbox B is changed, an event is fired to change span B.
However, in one particualar case I would like a change either textbox A or textbox B to update both span A and B. I tried wiring the events up to the corresponding controls in this case, but it didn't work because there is much state that is set up in the event building code (not to mention each event calls 'this', which would make the logic use the wrong control if it were fired from a different one than it was intended).
To make things easy, it would be best to pass a string (representing the other text input id) to the event handler at the time it is created, and then calling the change() event manually on the second control. However, this puts things in an infinite loop of recursion. I thought of a way to get around the recursion, but it reqires a global variable.
Is there a better way than this, preferably one that doesn't require a global variable?
ml_inEvent = false;
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event) {
// Other processing happens here...
if (event.data.controlToFire != '') {
var $controlToFire = $('#' + event.data.controlToFire);
if ($controlToFire.length) {
// Use a global variable to ensure this event is not fired again
// as a result of calling the other one
if (!ml_inEvent) {
ml_inEvent = true;
$controlToFire.change();
ml_inEvent = false;
}
}
}
});
You can use the extraParameters argument on .trigger() to break out, for example:
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event, fire) {
// Other processing happens here...
if(fire !== false) $('#' + event.data.controlToFire).trigger('change', false);
});
You can give it a try here. What this does is the event handler callback not only receives the event object but also any other arguments you pass in, in this case we're just using a simple false and a !=== check this in important so undefined (the parameter not passed at all) still changes both controls. So for instance $("#control").change() would change both controls, but still not loop...you can test that here.

Resources