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