gpt4 book ai didi

qt - 带有 QGridLayout 的 QDockWidget - 布局内的小部件不与顶部对齐

转载 作者:行者123 更新时间:2023-12-04 13:37:10 27 4
gpt4 key购买 nike

我正在尝试创建一个可停靠的工具栏(类似于您在 Photoshop 中使用的工具栏),它将包含一个 2 x (n) 的按钮网格。我的想法是使用一个 QGridLayout 的父级到一个空白 QWidget,它被添加到一个 QDockWidget,并将按钮添加到 QGridLayout。除了对齐之外,这似乎有效。

我已经为按钮设置了对齐...

myLayout->addWidget(button1,0,0,1,1,Qt::AlignTop);
myLayout->addWidget(button2,0,1,1,1,Qt::AlignTop);
myLayout->addWidget(button3,1,0,1,1,Qt::AlignTop);
myLayout->addWidget(button4,1,1,1,1,Qt::AlignTop);

...然而网格正在扩展到 QDockWidget 的整个高度,如下所示:
enter image description here

按钮也在水平扩展,以填充整个空间。我想我可以限制水平调整大小的能力(如果可能的话?)。

是否有我在文档中忽略的功能可以更好地控制 GridLayout 以限制它填充父小部件的整个宽度/高度?作为一个附带问题,有没有办法防止 QDOckWidget 在某个方向上重新调整大小?

最佳答案

来自 the documentation :

QGridLayout takes the space made available to it (by its parent layout or by the parentWidget()), divides it up into rows and columns, and puts each widget it manages into the correct cell.

Columns and rows behave identically; we will discuss columns, but there are equivalent functions for rows.

Each column has a minimum width and a stretch factor. The minimum width is the greatest of that set using setColumnMinimumWidth() and the minimum width of each widget in that column. The stretch factor is set using setColumnStretch() and determines how much of the available space the column will get over and above its necessary minimum.



所以最简单的方法是使用固定大小的可停靠小部件 QWidget::setFixedSize .一般来说,我不会推荐它(管理布局),但由于以下原因,它非常适合您的情况:
  • 所有按钮的大小都相同,因此您可以根据按钮的数量大致了解工具栏的大小。
  • 您不需要管理布局行为。
  • 您可以使用任一维度,或同时使用这两个维度

  • 例如,当添加按钮时
      void addButton(QWidget* w,QGridLayout* wl, QButton* button, posParams...){
    // w is the widget inside the QDockWidget (edit)
    //wl is w layout
    //break the constraints, the widget can be resized
    w->setFixedSize(QSize(QWIDGETSIZE_MAX,QWIDGETSIZE_MAX));
    // only line to change if you want to hide, remove widget
    wl->addWidget(button, params);
    //fit to contents
    w->adjustSize();
    // can be swapped to w->setFixedHeight, setFixedWidth
    w->setFixedSize(w->size());
    }

    尝试并验证在修改后停靠和取消停靠小部件时不会出错。你应该注意到打破约束也会打破
    布局。

    一般来说, QLayout::SizeConstraint 之间存在层次结构。 , QWidget::minimumSizeHint , QWidget::minimumSize ,您可以在文档中找到它。
  • QWidget::minimumSize默认情况下未设置。当它是时,它占上风QWidget::minimumSizeHint
  • QWidget::minimumSizeHint如果小部件不在布局中(这意味着可以用鼠标将其大小调整为 0),则无效,否则使用布局定义的那个。
  • QLayout::SizeConstraint保存它*直接*管理的小部件的默认布局行为。如果您嵌套布局 A在布局内 B ,所有小部件添加到 A将使用其属性(property)。此外,如果小部件 WB定义自己的布局,那么这个布局约束就是要应用于小部件的约束W .
  • 关于qt - 带有 QGridLayout 的 QDockWidget - 布局内的小部件不与顶部对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155430/

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