使QHBoxLayout在QWidget的实例中可访问

Make a QHBoxLayout accesible in an Instance of a QWidget

本文关键字:访问 实例 QHBoxLayout QWidget      更新时间:2023-10-16

我想子类化一个QWidget…

 Widget::Widget(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImgWidget)
{
    // Is this the right place or does it need to be outside like: Widget::layout...
    QHBoxLayout *hLayout = new QHBoxLayout;
    ...
    hLayout->addWidget( someWidget );
    this->setLayout(hLayout);
}

…然后在实例中,我想在布局中添加一个小部件,比如

Widget *widget = new Widget();
...
widget->hLayout->addWidget( someOtherWidget );

在Python中等效的可以通过'self'关键字来完成,比如self.layout = QHBoxLayout(),但我认为它不能用this关键字

来完成

但更普遍的是…在c++中最好的方法是什么?因为我经常用pyqt

任何QWidget都可以通过layout函数提供对布局的访问。

Widget* widget = new Widget();
QLayout* layout = widget->layout();

我不知道你为什么要从外部修改小部件的布局,但在这一点上,你需要了解实际的布局类型。有了布局类型的知识,你就可以强制转换和使用它。

QHBoxLayout* hLayout = qobject_cast<QHBoxLayout>(layout);

实现函数addSubWidget (QWidget* aubWidget),其余的代码是ok的,并使hLayout私有。或者,像@James建议的那样,使用带强制类型转换的layout函数。

在c++中,只是推荐,而不是强制使用this->hLayout,以确保您不会将其与同名的局部变量遮蔽