QScrollArea missing Scrollbar

柔情痞子 提交于 2019-11-28 12:40:12

You do not want to set the layout on the scroll area itself. The answer you cite stems from misunderstanding this.

  1. You need to have a widget within a scrollarea, and you pass that widget to the area using QScrollArea::setWidget. If all you have inside the scroll area is one widget with no children, then you don't need additional layout.

  2. You do not need to manually keep track of widgets that are owned by a layout. They'll be deleted automatically once the widget that has the layout is deleted.

  3. The QScrollArea widget is not laid out within its enclosing widget.

Below is a working example of how to do it:

// https://github.com/KubaO/stackoverflown/tree/master/questions/scroll-18703286
#include <QScrollArea>
#include <QVBoxLayout>
#include <QSpinBox>
#include <QApplication>

class Window : public QWidget
{
   QVBoxLayout m_layout{this};
   QScrollArea m_area;
   QWidget m_contents;
   QVBoxLayout m_contentsLayout{&m_contents};
   QSpinBox m_spinBoxes[10];
public:
   Window(QWidget *parent = {}) : QWidget(parent) {
      m_layout.addWidget(&m_area);
      m_area.setWidget(&m_contents);
      for (auto & spinbox : m_spinBoxes)
         m_contentsLayout.addWidget(&spinbox);
      m_contentsLayout.setSizeConstraint(QLayout::SetMinimumSize);
   }
};

int main(int argc, char *argv[])
{
   QApplication app(argc, argv);
   Window w;
   w.show();
   return app.exec();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!