【问题标题】:Load ImageList picture in TImage with a ComboBox使用 ComboBox 在 TImage 中加载 ImageList 图片
【发布时间】:2013-07-24 22:04:47
【问题描述】:

在我的 Delphi 表单中,我有一个带有 4 张图片的 ImageList。还有一个名为ComboBox1 的ComboBox 和一个名为Image9 的TImage 组件。

我为我的 ComboBox 创建了一个onChange,因为我想做这样的事情:如果选择了 ComboBox 项目 1,则将图像 1 加载到我的 ImageList 中。如果选择了 ComboBox 项目 3 相同的情况(例如),加载 ImageList 的图像 3。

我写的代码是这样的:

case ComboBox1.Items[ComboBox1.ItemIndex] of
0:
 begin
  ImageList1.GetBitmap(0,Image9.Picture);
 end;
1:
 begin
  ImageList1.GetBitmap(1,Image9.Picture);
 end;
2:
 begin
  ImageList1.GetBitmap(2,Image9.Picture);
 end;
3:
 begin
  ImageList1.GetBitmap(3,Image9.Picture);
 end;
end;

使用此代码,IDE(我正在使用 Delphi XE4)在 case ComboBox1.Items[ComboBox1.ItemIndex] of 上给我一个错误,因为它说需要 Ordinal 类型。我能做什么?

【问题讨论】:

  • case ComboBox1.ItemIndex of

标签: delphi


【解决方案1】:

case statements 在 Delphi 中工作于 Ordinal types:

序数类型包括整数、字符、布尔值、枚举和子范围类型。序数类型定义了一组有序值,其中除了第一个值之外的每个值都有一个唯一的前任,而除了最后一个之外的每个值都有一个唯一的后继。此外,每个值都有一个序数,它决定了类型的顺序。在大多数情况下,如果一个值的序数为 n,则其前身的序数为 n-1,其后继的序数为 n+1

ComboBox.Items 是字符串,因此不符合作为序数的要求。

另外,正如您在下面的comment 中所指出的,您不能按原样直接分配给Image9.Picture;您必须改用Image9.Picture.Bitmap。为了使TImage 正确更新以反映更改,您需要调用它的Invalidate 方法。)

将您的case 改为直接使用ItemIndex

case ComboBox1.ItemIndex of
  0: ImageList1.GetBitmap(0,Image9.Picture.Bitmap);
  1: ImageList1.GetBitmap(1,Image9.Picture.Bitmap);
end;
Image9.Invalidate;  // Refresh image

或者直接去ImageList

if ComboBox1.ItemIndex <> -1 then
begin
  ImageList1.GetBitmap(ComboBox1.ItemIndex, Image9.Picture.Bitmap);
  Image9.Invalidate;
end;

【讨论】:

  • 最后一个解决方案严重减少了代码量。但是不要忘记检查ItemIndex是否为-1,即是否没有选中任何项目。或者将样式设置为 DropDownList 并在显示表单之前设置 itemindex,以确保永远无法选择 -1
  • @GolezTrol:好点。我将编辑以添加该检查,但如果用户需要从 ComboBox 中选择一个,我会希望样式已经是 DropDownList。
  • 对不起,我迟到了。顺便说一下+1,非常有用且完整的答案:)谢谢!
  • @KenWhite 我注意到,如果您使用“Image9.Picture”,代码将不起作用。相反,使用 Image9.Picture.Bitmap 是正确的 :)
  • @DK64:感谢您提供的信息;我没有仔细看那部分代码。我已将其添加为未来读者的注释,并更新了代码以反映这一点。感谢您的支持并接受。 :-)
猜你喜欢
  • 2011-02-18
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
相关资源
最近更新 更多