加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – ComboBox:每个项目上的一个按钮(从列表中删除项目)

发布时间:2020-12-15 04:35:09 所属栏目:大数据 来源:网络整理
导读:我需要在ComboBox的每个项目上添加一个按钮(可能是TSpeedButton?).单击该按钮时,将从列表中删除相应的项目.例如: 我在字符串网格中看到过类似的关于SpeedButtons的讨论(这里:TStringGrid with SpeedButtons),但我不知道如何在ComboBox上实现所有这些东西.
我需要在ComboBox的每个项目上添加一个按钮(可能是TSpeedButton?).单击该按钮时,将从列表中删除相应的项目.例如:

我在字符串网格中看到过类似的关于SpeedButtons的讨论(这里:TStringGrid with SpeedButtons),但我不知道如何在ComboBox上实现所有这些东西.能否请您给我一些建议或链接,以便进一步阅读该主题.

解决方法

除了用户体验评论之外,我同意这个问题的解决方案并不是那么难.

您可以通过将Style属性设置为csOwnerDrawFixed,在OnDrawItem事件中自己绘制项目,并在OnSelect事件中删除所选项目来完成此操作,例如,如下所示:

unit Unit1;

interface

uses
  Winapi.Windows,System.Classes,Vcl.Controls,Vcl.Forms,Vcl.StdCtrls,Vcl.Imaging.PNGIMage;

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer;
      Rect: TRect; State: TOwnerDrawState);
    procedure ComboBox1Select(Sender: TObject);
  private
    FDeleteGraphic: TPNGImage;
    FDeleteRect: TRect;
  end;

implementation

{$R *.dfm}

{ TForm1 }

procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
begin
  ComboBox1.Canvas.FillRect(Rect);
  if Index >= 0 then
    ComboBox1.Canvas.TextOut(Rect.Left + 2,Rect.Top,ComboBox1.Items[Index]);
  if (odSelected in State) and not (odComboBoxEdit in State) then
  begin
    FDeleteRect := Rect;
    FDeleteRect.Left := FDeleteRect.Right - FDeleteGraphic.Width;
    ComboBox1.Canvas.Draw(FDeleteRect.Left,FDeleteRect.Top,FDeleteGraphic);
  end;
end;

procedure TForm1.ComboBox1Select(Sender: TObject);
var
  MousePos: TPoint;
begin
  MousePos := ComboBox1.ScreenToClient(Mouse.CursorPos);
  MousePos.Offset(0,-ComboBox1.Height);
  if PtInRect(FDeleteRect,MousePos) then
  begin
    ComboBox1.Items.Delete(ComboBox1.ItemIndex);
    ComboBox1.Invalidate;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FDeleteGraphic := TPNGImage.Create;
  FDeleteGraphic.LoadFromFile('H:IconsFamFam CommonDelete.png');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FDeleteGraphic.Free;
end;

end.

有了这个结果:

您可能希望(重新)存储先前的ItemIndex设置.根据您的意愿定制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读