作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在 Windows 7 上使用 Qt5。在我当前的应用程序中,我有以下代码可以更改某些按钮的背景颜色:
...
for(int i = 0; i < layout()->count(); i++)
{
QPushButton * button = static_cast<QPushButton*>(layout()->itemAt(i)->widget());
button->setStyleSheet(backgroundColor);
}
好吧,我对上面的代码有 2 个问题:
可以/正确使用 static_cast
还是我应该使用其他类型的转换?
是否可以使用 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/
我是一名优秀的程序员,十分优秀!