c++ - QFormLayout 中的 QSpacerItem - 垂直展开

标签 c++ qt

我想在我的QFormLayout中强制扩展空间,但无论怎样QFormLayout只使用QSpaceItem::sizeHint() .有谁知道解决此问题的方法或处理此问题的正确方法吗?


MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
   SetupLayout();
}

void MyWidget::SetupLayout()
{
   QFormLayout * layout = new QFormLayout();

   layout->addRow("Something1", new QComboBox());
   layout->addRow("Something2", new QSpinBox());

   //Spacer
   layout->addItem(new QSpacerItem(0,10, QSizePolicy::Expanding, QSizePolicy::Expanding));

   layout->addRow(QPushButton("Something3"));

   setLayout(layout);
}

最佳答案

所以有几个不同的问题:

  1. QFormLayout 不像其他布局那样扩展。我的小部件(其中一些)被放置在 QFormLayout 中。这阻止了他们扩张。我将我的主要父布局从 QFormLayout 切换到了 QVBoxLayout。这让我不得不使用 QLayout::setAlignment(Qt::AlignTop)
  2. 这解决了我的其他一些小部件无法扩展的一些问题。然而,这些小部件使用了 QVBoxLayout。上面的小部件使用 QFormLayout。为了得到这个扩展,我必须在我的 QSpacerItem 中使用以下行:

QSpacerItem * my_spacer = new QSpacerItem(0,1000, QSizePolicy::Expanding, QSizePolicy::Expanding);


我正在提供一些示例代码。目标是显示层次结构,以及 QFormLayout 会在哪里造成麻烦。

示例代码:

//A main Widget class
void SetupLayout()
{
   QHBoxLayout * main_layout = new QHBoxLayout();

   main_layout->addWidget(Some_Widget);

   //Create a control widget
   control_widget = new QWidget();  // IMPORTANT control_widget is a member
   QVBoxLayout * layout = new QVBoxLayout(); //IMPORTANT!!!! - Here it was QFormLayout

   layout->setAlignment(Qt::AlignTop); //IMPORTANT - Needed this after switching to QVBoxLayout

   layout->addWidget(new QComboBox("stuff")); //Some combo box
   control_widget->setLayout(layout);

   main_layout->addWidget(control_widget);
}

//Later on, we have a "Put a new widget in the control area" task
void NewControlArea()
{
   if(current_control)
      control_widget->removeWidget(current_control);  //current_control is a member variable

   current_control = new MyWidget();  //FROM ABOVE
   control_widget->addWidget(current_control);
}

如果 MyWidget 使用 QFormLayout,除非我添加带有大小提示的间隔符,否则不会展开内容。但是,如果 MyWidget 使用 QVBoxLayout,则其中的任何 QWidgets 都会正确展开。

关于c++ - QFormLayout 中的 QSpacerItem - 垂直展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828657/

相关文章:

c++ - boost find in shared-memory方法卡在c++多进程项目中

c++ - 我如何使用 QProcess 的队列?

c++ - 我如何使用 Qt Creator 将一个对象的值从一个窗口获取到另一个窗口的类中?

c++ - 如何访问 ttf 字体(不是 otf)的 GDEF/GPOS/GSUB?

c++ - 从方法返回后局部结构变量不会被销毁

qt - 检测到由布局管理的项目上的 anchor 。这是未定义的行为;使用 Layout.alignment 代替

c++ - 如何使用QString toUtf8和fromUtf8?

c++ - 检查 QPainterPath 中是否存在点

c++ - 在 MFC 上选择多个 UINT 格式时出现语法错误

c++ - 传递对 STL vector 中偏移位置的引用