QFormLayout的第二个条目如何换行? 附上实际和预期结果图像

问题描述

我正在使用 qformlayout,但行的第二项没有被垂直包裹。

.ui 文件内容

   <widget class="QScrollArea" name="scrollArea">
          <property name="widgetResizable">
           <bool>true</bool>
          </property>
          <widget class="QWidget" name="scrollAreaWidgetContents">
           <property name="geometry">
            <rect>
             <x>0</x>
             <y>0</y>
             <width>524</width>
             <height>281</height>
            </rect>
           </property>
           <layout class="qformlayout" name="flPatientInfo">
            <property name="rowWrapPolicy">
             <enum>qformlayout::WrapLongRows</enum>
            </property>
            <property name="verticalSpacing">
             <number>5</number>
            </property>
           </layout>
          </widget>
         </widget>
        </item>
       </layout>
      </widget>

添加行的代码 -

  for (auto info : patientInfo.toStdMap())
  {
    QLabel *fieldData = new QLabel(GetTranslatedString(info.second.second));
    fieldData->setProperty("FieldData",true);
    m_GUI->m_UI->flPatientInfo->addRow(GetTranslatedString(info.second.first),fieldData); 
  }

实际结果

Actual Result

预期结果

Expected Result

解决方法

QFormLayout::RowWrapPolicy 必须处理标签和小部件的布局方式,而不是小部件是否损坏。如果标签 + 小部件的可用空间不足,则在使用 QFormLayout::WrapLongRows 时,小部件将简单地布置在新行中。

您添加一个 QLabel 作为小部件,它通常不会破坏文本,而是写成一行。您需要使用 setWordWrap:

在该标签上启用自动换行
for (auto info : patientInfo.toStdMap())
{
    QLabel *fieldData = new QLabel(GetTranslatedString(info.second.second));
    fieldData->setProperty("FieldData",true);
    fieldData->setWordWrap(true); // HERE
    m_GUI->m_UI->flPatientInfo->addRow(GetTranslatedString(info.second.first),fieldData); 
}