qobject_cast<QVBoxLayout*>(layout()),是否合适?

qobject_cast<QVBoxLayout*>(layout()), is the appropriate cast?

考虑到布局是在 QWidget 中使用以下代码设置的:

setLayout(new QVBoxLayout);

然后需要检索它(向布局添加更多内容)。这是通过以下代码完成的:

QHBoxLayout *hLayoutTime(new QHBoxLayout);
qobject_cast<QVBoxLayout*>(layout())->addLayout(hLayoutTime);

qobject_cast 是适合在这里使用的转换类型吗?

为了避免不必要的转换,这样写:

void YourWidget::setupContents()
{
     QVBoxLayout *vLayout = new QVBoxLayout(this); // effectively this does setLayout(new QVBoxLayout);

     QHBoxLayout *hLayoutTime(new QHBoxLayout);
     vLayout->addLayout(hLayoutTime);
     … … …
}

查看您当前示例中的代码,为什么不在创建时直接获取指针?

auto *vLayout = new QVBoxLayout;
auto *hLayoutTime = new QHBoxLayout;
vLayout->addlaout(hLayoutTime);

回答你的问题,最合适的演员表可能是:

dynamic_cast<QHBoxLayout*>(new QVBoxLayout);

dynamic_cast 比 static_cast 有几个检查和好处,因此最好尽可能使用它。