1
votes

http://doc.qt.io/qt-4.8/qgridlayout.html#QGridLayout-2

What does the following quote mean?

You must insert this grid into another layout. You can insert widgets and layouts into this layout at any time, but laying out will not be performed before this is inserted into another layout.

I have not inserted it into any layout nor I have set the parent. Why is this working?

void Screen::displayWordOnScreen()
{
    for (uint i = 0; i < NumOfBlanks; i++)
    {
        blank[i] = createBlank (SLOT (blankFilled (QString)));
    }

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->setSizeConstraint (QLayout::SetFixedSize);

    for (uint i = 0; i < NumOfBlanks; i++)
    {
        mainLayout->addWidget (blank[i], 0, i);
    }

    setLayout (mainLayout);
}
2

2 Answers

1
votes

It's a documentation bug. Pure and simple.

The setMainLayout call is redundant. You can set a layout by giving the widget it should act on as its parent:

 auto mainLayout = new QGridLayout(this);

You also don't need to create the layout dynamically - it can be kept by value. Since it seems that NumOfBlanks is a compile-time constant, you could simplify it all:

class Blank : public QWidget {
  Q_OBJECT
public:
  Q_SIGNAL void blankFilled(const QString &);
  ...
};

class Screen : public QWidget {
  Q_OBJECT
  enum { NumOfBlanks = 10; }
  QGridLayout m_layout(this);
  std::array<Blank, NumOfBlanks> m_blanks;
  void onBlankFilled(Blank *, const QString &);
public:
  explicit Screen(QWidget *parent = nullptr);
  void displayWordOnScreen();
};

Screen::Screen(QWidget *parent) : QWidget(parent) {
  int i = 0;
  for (auto &blank : m_blanks) {
    connect(&blank, &Blank::blankFilled, [&](const QString &){
      onBlankFilled(&blank, data);
    });
    m_layout.addWidget(&blank, 0, i++);
    blank.hide();
  }
  m_layout.setSizeConstraint(QLayout::SetFixedSize);
}

void Screen::displayWordOnScreen() {
  for (auto &blank : m_blanks)
    blank.show();
}
1
votes

I don't know why the docs are written like that, but you don't have to add layouts to layouts. You can, but you don't have to.

You can set a layout to a widget like you're doing in your code. In fact at some point you have to do that. If you would have to add each layout to another layout, then you wouldn't have a layout that manages the widget's layout. You'd just have layouts that do nothing. So that sentence in the docs makes no sense.