自定义 QScrollArea 小部件

Custom QScrollArea widget

我正在尝试创建一个从 QScrollArea 派生的 class,因此我可以在表单编辑器中将 ScrollArea 提升为我的自定义 class。 我有这个代码:

#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include "CustomScrollArea.h"

CustomScrollArea::CustomScrollArea(QWidget *parent) :
QScrollArea (parent)
{
    setWidgetResizable( true );

    QWidget *widget = new QWidget();

    QVBoxLayout *layout = new QVBoxLayout();
    widget->setLayout( layout );

    setWidget( widget );

    for (int i = 0; i < 10; i++)
    {
        QPushButton *button = new QPushButton( QString( "%1" ).arg( i ) );
        layout->addWidget( button );
    }
}

我遇到的问题是按钮不是那样显示的...

.ui内容:

...
<widget class="QWidget" name="centralWidget">
   <widget class="CustomScrollArea" name="scrollArea">
    <property name="geometry">
     <rect>
      <x>40</x>
      <y>40</y>
      <width>221</width>
      <height>201</height>
     </rect>
    </property>
    <property name="widgetResizable">
     <bool>true</bool>
    </property>
    <widget class="QWidget" name="scrollAreaWidgetContents">
     <property name="geometry">
      <rect>
       <x>0</x>
       <y>0</y>
       <width>219</width>
       <height>199</height>
...

问题不是由您显示的代码引起的,而是由 Qt Designer 引起的,Qt Designer 设置了一个默认值 scrollAreaWidgetContents,它在 QScrollArea 中设置,替换了以前的小部件。

 ...
 <widget class="CustomScrollArea" 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>380</width>
     <height>215</height>
    </rect>
   </property>
  </widget>
 </widget>
 ...

因此解决方案是手动删除这些行,使用支持 XML 的编辑器打开 .ui 并进行编辑以获得以下内容:

 ...
 <widget class="CustomScrollArea" name="scrollArea">
  <property name="widgetResizable">
   <bool>true</bool>
  </property>
 </widget>
 ...

然后保存修改并编译。