Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Is it possible to do that using spacer?



  • Hi,
    I have simple app: mainWindow with gridLayout and 4 labels in this grid.

    My code:

        grid = new QGridLayout;
        l1 = new QLabel;
        l2 = new QLabel;
        l3 = new QLabel;
        l4 = new QLabel;
    
        l1->setFixedSize(200,50);
        l2->setFixedSize(200,50);
        l3->setFixedSize(200,50);
        l4->setFixedSize(200,50);
    
        l1->setStyleSheet("QLabel {background:red}");
        l2->setStyleSheet("QLabel {background:blue}");
        l3->setStyleSheet("QLabel {background:yellow}");
        l4->setStyleSheet("QLabel {background:green}");
    
        centralWidget()->setLayout(grid);
    
        grid->addWidget(l1, 0,0);
        grid->addWidget(l2, 0,1);
        grid->addWidget(l3, 1,0,Qt::AlignLeft);
        grid->addWidget(l4, 1,1,Qt::AlignRight);
    

    Now I have:
    now.png

    But I would like to have:
    want.png

    I know that I can use Spacer, but I don't know how.



  • @qwe3 said in Is it possible to do that using spacer?:

    I know that I can use Spacer, but I don't know how.

    No need. This works for me.

    grid->addWidget(l1, 0,0, Qt::AlignCenter);
    grid->addWidget(l2, 0,1, Qt::AlignCenter);
    grid->addWidget(l3, 1,0, Qt::AlignVCenter | Qt::AlignLeft);
    grid->addWidget(l4, 1,1, Qt::AlignVCenter | Qt::AlignRight);
    

Log in to reply