سؤال

I'm developing a little game in C++ Qt 4.6.3 and I stumbled upon a layout-issue. The layout I'm looking for is a 3x3 QGridLayout of which the central cell (1,1) holds the main widget (it's a board game). The (0,1)-cell should hold a QLabel displaying whos turn it is, the (1,0) and (1,2) cells are subdivided into QVBoxLayouts to hold a maximum of 3 scoreboards, and the (2,1)-cell also holds some kind of QLabel.

Image of the layout

This is what I've got so far:

QGridLayout *mainLayout = new QGridLayout(this);
QVBoxLayout *leftLayout = new QVBoxLayout;
QVBoxLayout *rightLayout = new QVBoxLayout;  
mainLayout->addLayout(leftLayout,   1, 0, AlignTop);
mainLayout->addWidget(topText,      0, 1, AlignCenter);
mainLayout->addWidget(board,        1, 1);
mainLayout->addLayout(bottomText,   2, 1, AlignCenter);
mainLayout->addLayout(rightLayout,  1, 2, AlignTop);

Now, on MS Windows (laptop of my GF) I solved this by reimplementing the resizeEvent() function:

void Game::resizeEvent(QResizeEvent *)
{
    mainLayout->setRowMinimumHeight(1, 0.8 * height());
    mainLayout->setColMinimumWidth(1, 0.8 * height());
    // some other stuff
}

This worked fine! However, on Unix there seems to be a problem (or could it be due to a version difference? 4.6 vs 4.8). On calling the setRowMininmumHeight() method, it seems that another resize-event is issued, resulting in a recursive call! I want my application to work on both platforms, so clearly I had to find another solution. I fiddled around with setRowStretch() and setColStretch() but neither of those had the desired result. I tried all sorts of combinations but now I am quite stuck...

Does anyone have a solution to this seemingly easy problem?

هل كانت مفيدة؟

المحلول

You should use stretches rather than minimum sizes to solve the problem. Execute this code after adding the widgets to the layout to assign 80% of the height to the middle row:

mainLayout->setRowStretch(0, 1); // 10% for top row
mainLayout->setRowStretch(1, 8); // 80% for middle row
mainLayout->setRowStretch(2, 1); // 10% for bottom row

Note that minimum size constraints of the contained widgets are still respected (unless you set the size policy to ignored). So if you want to assign the whole height minus the two minimum sizes of the rows 0 and 2 (as you are saying they should be "as small as possible"), assign 100% to the middle row and 0% to the rows 0 and 2; they still respect the minimum sizes:

mainLayout->setRowMinimumHeight(0, 20); // 20px for top row
mainLayout->setRowMinimumHeight(2, 20); // 20px for bottom row
mainLayout->setRowStretch(0, 0);
mainLayout->setRowStretch(1, 1); // remaining height for middle row
mainLayout->setRowStretch(2, 0);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top