需要实现功能:checkbox模拟radiobutton功能
因为checkbox的checked的改变有三种方式,
第一种是直接调用语句:checkbox.checked:=true/false;第二种是直接点击这个控件,当然前提是要有checkboxClick事件.
第三种是state 表示复选框的当前状态.
cbchecked 表示选中,
cbunchecked表示未选中,
cbGrayed表示变灰状态.(allowgrayed 设置true时)
直接点击checkbox的时候要发生一组反应,比如界面上数据的显示变化.而当直接用第一种方法 (checkbox.checked:=true)时,要求没有什么变化,只要打个勾就行了.但这样的语句调用会激发checkbox的 onclick事件,而这是我不想看到的结果.
解决方法:使用焦点(Focused)来区别操作.
就是checkbox的焦点.如果是点击的话,则其焦点就应该为true,
而用语句改变时,checkbox的焦点不为true.这样就能区分两种情况了,
在checkbox的onclick事件中加入的焦点判断这一个条件.
if not chkRelation.Focused then Exit;
案例:
Form上面有2个checkbox:A和B,点击勾选其中一个,自动取消另外一个,并且必须有一个按钮选中,和radiobutton效果一样
第一步实现按钮切换效果,但是选中一个后再点击它就会取消选中,例如选中A自动取消选择B,再点击A,A也会取消选中状态,即A和B都未选中:
procedure TForm1.checkbox1Click(Sender: TObject);
begin
if not checkbox1.Focused then Exit;
checkbox2.Checked := False;
end;
procedure TForm1.checkbox2Click(Sender: TObject);
begin
if not checkbox2.Focused then Exit;
checkbox1.Checked := False;
end;
第二步实现radiobutton最终效果:
procedure TForm1.checkbox1Click(Sender: TObject);
begin
if not checkbox1.Focused then Exit;
checkbox1.ReadOnly := True;
checkbox2.ReadOnly := False;
checkbox2.Checked := False;
end;
procedure TForm1.checkbox2Click(Sender: TObject);
begin
if not checkbox2.Focused then Exit;
checkbox2.ReadOnly := True;
checkbox1.ReadOnly := False;
checkbox1.Checked := False;
end;