我正在寻找一些 BCB 代码来迭代表单上的控件并获取有关它们的一些信息。
我尝试使用 myForm->ControlCount
和 typeid(myForm->Controls[i])
但这给了我一些问题。
1) typeid(myForm->Controls[i])->Name
总是给出 "TControl *"
我希望得到“TEdit *”、“TMemo *”等
我可以使用
来解决这个问题吗if (typeid(myForm->Controls[i]) == typeid(TEdit))
然后类型转换? (如果是这样,如何转换最好?)
2) 我如何(可能通过转换)获得控件的属性?例如,名称、宽度、高度等?
我真的很喜欢这里的实际代码(或一些实际代码的 URL);谢谢。
更新:因为我只需要针对我的特定情况测试 5 或 6 种不同类型的控件,我想我可以尝试 dynamic_cast<>
每个人依次给他们每个人,但我似乎无法让它工作......
最佳答案
您假设强制转换是一个好主意并且使用 dynamic_cast
是这里的最佳选择,这在某种程度上是正确的。
如果您想遍历表单(或任何其他容器)的控件。不幸的是,我在这台计算机上没有我的 C++ Builder,所以我无法测试我给你的代码,虽然创建起来应该是一个微不足道的任务。
// You wanna start my iterating through the controls of the container
for (int i = 0; i < container->ControlCount; i++)
{
// Let us extract the control at index i
TControl *control = container->Controls[i];
// Now we want to test whether this is any specific type, for instance a
// TEdit or any TEdit descendant.
TEdit *edit = dynamic_cast<TEdit *>(control);
// If this control is a TEdit or any control deriving from it, we will have
// a pointer to it, if this is any other type, we will be left with a zero
// pointer.
if (edit)
{
// This is a TEdit control... we can now access TEdit only properties.
edit->Text = "This is an edit control.";
}
// We do the same if we want to test for a TButton...
TButton *button = dynamic_cast<TButton *>(control);
// Again we test whether this was actually a button
if (button)
{
// It is a button, again we can access TButton only properties...
button->Caption = "This is a button";
// Yeah ok not a TButton only one, but couldn't think of any.
}
// And so on...
}
您不需要为子控件的子控件递归函数,这些也包含在 VCL 中。在我看来,这是迄今为止测试特定类型的最简单的解决方案。我也尽量避免使用 RTTI 功能,但我就是这样。
如您所见,我的示例还展示了如何访问控件的属性和函数,甚至是特定于特定类型的属性和函数。但是,您提到的那些:Name
、Width
和 Height
对 TControl
都是通用的,因此没有必要转换以访问这些。
希望这对您有所帮助,从我的示例中应该清楚,变量 container
可以替换为您在自己的示例中使用的 myForm
。
关于c++builder - BCB : how to iterate over controls on a form?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2391325/