Custom QScrollArea widget

I am trying to create a class derived from QScrollArea, so I can promote ScrollArea to my custom class in form editor. I have this code:

#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 );
    }
}

the problem I have is that buttons are not displayed that way...

the .ui contents:

...
<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>
...

Upvotes: 2

Views: 664

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

The problem is not caused by the code you shows but by Qt Designer, Qt Designer sets a default scrollAreaWidgetContents that is set in the QScrollArea replacing the previous widget.

enter image description here

 ...
 <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>
 ...

So the solution is to manually remove those lines, open the .ui with an editor that supports XML and do that editing obtaining the following:

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

Then save the changes and compile.

Upvotes: 3

Related Questions