2
votes

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>
...
1
_ buttons are not displayed that way_ I am not able to find an evidence for that. Your code produces: i.stack.imgur.com/O4BeJ.png - scopchanov
@scopchanov I have reproduced the problem, it only happens if the layout is created inside the constructor, if you do it after that, the problem is not generated. - eyllanesc
maybe it only doesn't work on mac... I don't know... I get an empty scroll area, - Александр Литвицкий
@АлександрЛитвицкий It seems to me that it is a bug, in linux I also have that problem. - eyllanesc
@scopchanov The problem is when they promote it, read my answer. - eyllanesc

1 Answers

3
votes

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.