gpt4 book ai didi

c++ - Qt/C++ : Is "static_cast" ok for casting in this snippet of code?

转载 作者:太空狗 更新时间:2023-10-29 23:26:18 24 4
gpt4 key购买 nike

我在 Windows 7 上使用 Qt5。在我当前的应用程序中,我有以下代码可以更改某些按钮的背景颜色:

...
for(int i = 0; i < layout()->count(); i++)
{
QPushButton * button = static_cast<QPushButton*>(layout()->itemAt(i)->widget());
button->setStyleSheet(backgroundColor);
}

好吧,我对上面的代码有 2 个问题:

  1. 可以/正确使用 static_cast 还是我应该使用其他类型的转换?

  2. 是否可以使用 foreach 代替上面的 for 循环

最佳答案

你应该使用 qobject_cast这样您就可以检查转换是否成功。如果转换失败则返回 0。

QPushButton * button = qobject_cast<QPushButton*>(layout()->itemAt(i)->widget());
if(button)
// cast ok
else
// cast failed

您不能使用 foreach因为你需要一个容器。

关于c++ - Qt/C++ : Is "static_cast" ok for casting in this snippet of code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com