简体   繁体   English

父级小部件中的中心子级小部件(在布局中添加了父级小部件)

[英]Center children widget in parent widget(parent widget was added in layout)

I created a layout contain a parent widget . 我创建了一个包含父部件布局 In that parent widget i created another widget. 在该父窗口小部件中,我创建了另一个窗口小部件。

My code is similarly to this: 我的代码与此类似:

QGridLayout *layout = new QGridLayout();
QWidget *parentWidget = new QWidget();
layout->addWidget(parentWidget );
QWidget *childWidget = new QWidget(parentWidget);

在此处输入图片说明

How can i center the child widget in parent widget ? 如何将子窗口小部件放在父窗口小部件的中心?

The problem is we cannot get the true size of parent widget because it's in a layout. 问题是我们无法获得父窗口小部件的真实大小,因为它在布局中。

You can do this by setting fixed size of child widget and placing it inside grid layout of parent widget. 您可以通过设置子窗口小部件的固定大小并将其放置在父窗口小部件的网格布局中来执行此操作。

QGridLayout *layout = new QGridLayout();
QWidget *parentWidget = new QWidget();
layout->addWidget(parentWidget );
QWidget *childWidget = new QWidget(parentWidget);
QGridLayout *parentLayout = new QGridLayout();
parentWidget->setLayout(parentLayout);
parentLayout->addWidget(childWidget);
childWidget->setFixedSize(/*some fixed size for child widget*/);

Move the child inside the parent's showeEvent . 将孩子showeEvent父母的showeEvent You can use a bool flag to do it only when the parent is shown for the first time. 仅当第一次显示父项时,才可以使用bool标志来实现。

void Parent::showEvent(QShowEvent *)
{
    if(_first_show)
    {
        _first_show = false;
        _child->move(this->rect().center() - _child->rect().center());
    }
}

Proof that it works (red is the parent, and blue is the child): 证明有效(红色是父级,蓝色是子级):

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM