Important: Please read the Qt Code of Conduct -

QGridLayout replacing problem(in puctures)

  • I have problem of placing widgets in QGridLayout. I replace ships onMouseWeeling(I want to make them horizontal o vertical). But first type they place correctly, after it they place bad.
    First placing:
    second placing:
    but must be:

    How can I solve this problem?
    Thks in advance.

  • From the picture it seems you correctly swapped the row span and column span, but the row and column parameters are the same as the horizontal placing when they should also be swapped.

  • I don't think so, I think that problem is in updating.
    Here is a code of replacing:
    @void MainWindow::setUpShips() {
    if (shipsLayout) {
    delete shipsLayout;
    shipsLayout = new QGridLayout;
    if (Ship::orientation == Ship::HORIZONTAL) {
    shipsLayout->addWidget(ships[3], 0, 0, 1, 2);
    shipsLayout->addWidget(ships[2], 1, 0, 1, 2);
    shipsLayout->addWidget(ships[1], 2, 0);
    shipsLayout->addWidget(ships[0], 2, 1);
    } else {
    shipsLayout->addWidget(ships[3], 0, 0, 2, 1);
    shipsLayout->addWidget(ships[2], 0, 1, 2, 1);
    shipsLayout->addWidget(ships[1], 0, 2);
    shipsLayout->addWidget(ships[0], 1, 2);

  • Do you call addLayout or setLayout after that, to reapply the layout ?

  • I don't reapply the layout.
    I place all components one time in the constructor of MainWindow.
    @startButton = new QPushButton(tr("Start"));
    restartButton = new QPushButton(tr("Restart"));

    shipsLayout = 0;
    playerScoreLable = new QLabel("Your score");
    compScoreLable = new QLabel("Computer score");
    playerScoreEdit = new QLineEdit("0");
    compScoreEdit = new QLineEdit("0");


  • If you delete the layout in setUpShips, you should somehow "reattach" the new layout to the MainWindow.
    So where is the line that either set shipsLayout as a widget layout, or that adds shipsLayout to another layout ?

    But you could probably reuse the same layout with
    @if (!shipsLayout) {
    shipsLayout = new QGridLayout;

    instead of

    @if (shipsLayout) {
    delete shipsLayout;
    shipsLayout = new QGridLayout;@

    Widgets that are already present in the layout will simply move to their new position.

  • Thank you very much). Your advice has solved my problem perfectly.

Log in to reply