2
votes

I'm trying to lay out a grid of square custom (subclassed) QWidgets inside a QGridLayout and QScrollArea.

The way I want it to work is choosing the number of QGridLayout columns and creating squares of the correct sizes.

What I've tried doing already is

  1. Manually laying out/resizing the QWidgets but this was sloppy and slow
  2. Setting QScrollArea::widgetsResized to true which does resize the width correctly, but not the height, see screenshot.

I've tried setting QSizePolicy and overriding QWidget::heightForWidth along with setting QScrollArea::widgetsResized in my custom QWidget-derived class, like so:

CustomWidget::CustomWidget(...) 
{  
  ...

  QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred);
  policy.setHeightForWidth(true);

  setSizePolicy(policy);
}

...

int CustomWidget::heightForWidth(int width) const
{
    return width; // square
}

But CustomWidget::heightForWidth is never called.

Any help would be appreciated.

EDIT: I already did what this answer suggested, my custom widgets are in a layout (QGridLayout).

1
possible duplicate of QWidget::heightForWidth() is not calledm.s.
Did you try calling setFixedSize on each widget?Pavel Strakhov
@PavelStrakhov I don't want a fixed size, I want the same height as every (variable) width. I tried overriding sizeHints() but it didn't work for this since I need to return both width and height in that method.blashyrk
@m.s. It's not a duplicate since I'm doing what the accepted answer suggested. My custom QWidgets already are in a layout. Also, you might want to actually read the question the next time you mark something as a duplicate. Thanks.blashyrk

1 Answers

3
votes

It seems that you're missing hasHeightForWidth implementation. The following snippet works fine:

class MyWidget : public QTextEdit {
public:
  MyWidget() {}
  int heightForWidth(int width) const {
    return width;
  }
  bool hasHeightForWidth() const {
    return true;
  }
};
//...
QScrollArea area;
QWidget* widget = new QWidget();
QGridLayout* layout = new QGridLayout(widget);
area.setWidget(widget);
area.setWidgetResizable(true);
for(int row = 0; row < 10; row++) {
  for(int column = 0; column < 4; column++) {
    layout->addWidget(new MyWidget(), row, column);
  }
}
area.show();