简体   繁体   English

通过 Tag 属性查找 TImage

[英]Finding a TImage by its Tag property

I am using C++Builder and I have 64 TImage controls with different Tag values.我正在使用 C++Builder,我有 64 个具有不同Tag值的TImage控件。 Can I find an Image by its Tag somehow?我能以某种方式通过标签找到图像吗? I need this because my function has to move between two objects (which are Images) by adding 1 to their Tag s.我需要这个,因为我的 function 必须通过将 1 添加到它们的Tag来在两个对象(它们是图像)之间移动。 I am using the VCL library.我正在使用 VCL 库。

There is no function available in the VCL to do this for you. VCL 中没有可用的 function 可以为您执行此操作。 You will have to manually loop through the Components[] property of the owning TForm , or the Controls[] property of the Parent of the TImage controls, checking each component/control for TImage before accessing their Tag , eg:您将不得不手动遍历拥有TFormComponents[]属性或TImage控件的ParentControls[]属性,在访问TImage之前检查每个组件/控件的Tag ,例如:

TImage* TMyForm::FindImageByTag(NativeInt ATag)
{
    for(int i = 0; i < ComponentCount /* or: SomeParent->ControlCount */; ++i)
    {
        if (TImage *img = dynamic_cast<TImage*>(Components[i] /* or: SomeParent->Controls[i] */))
        {
            if (img->Tag == ATag)
                return img;
        }
    }
    return NULL;
}
TImage *img = FindImageByTag(...);
if (img)
    img->Tag = img->Tag + 1;

Alternatively, you should store pointers to your TImage controls in your own array, which you can then index into/loop through when needed, eg:或者,您应该将指向您的TImage控件的指针存储在您自己的数组中,然后您可以在需要时对其进行索引/循环,例如:

private:
    TImage* Images[64];

...

__fastcall TMyForm::TMyForm(TComponent *Owner)
    : TForm(Owner)
{
    Images[0] = Image1;
    Images[1] = Image2;
    Images[2] = Image3;
    ...
    Images[63] = Image64;
}

TImage* TMyForm::FindImageByTag(NativeInt ATag)
{
    for(int i = 0; i < 64; ++i)
    {
        if (Images[i]->Tag == ATag)
            return Images[i];
    }
    return NULL;
}

When populating the array, if you don't want to hard-code the 64 pointers individually, you can use a loop instead:填充数组时,如果您不想单独对 64 个指针进行硬编码,则可以使用循环:

__fastcall TMyForm::TMyForm(TComponent *Owner)
    : TForm(Owner)
{
    int idx = 0;
    for(int i = 0; (i < ComponentCount /* or: SomeParent->ControlCount */) && (idx < 64); ++i)
    {
        TImage *img = dynamic_cast<TImage*>(Components[i] /* or: SomeParent->Controls[i] */)
        if (img)
            Images[idx++] = img;
    }
}

Alternatively, using the Form's FindComponent() method:或者,使用 Form 的FindComponent()方法:

__fastcall TMyForm::TMyForm(TComponent *Owner)
    : TForm(Owner)
{
    int idx = 0;
    for(int i = 1; i <= 64; ++i)
    {
        TImage *img = dynamic_cast<TImage*>(FindComponent(_D("Image")+String(i)));
        if (img)
            Images[idx++] = img;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM