Carthusianorum
Carthusianorum

Reputation: 19

How to align QLabel correctly in a QGridLayout?

I am trying to align QLabels in a simple GridLayout but this doesn't work seems to be a bug in QT 5.9 ?

Here is my snippet, everything is in a QDialog:

MyDialogue::MyDialogue(QWidget *parent) : QDialog(parent) {
    QLabel *labelA = new QLabel(); labelA->setFixedSize(100, 25);
    QLabel *labelB = new QLabel(); labelB->setFixedSize(100, 25);
    QLabel *labelC = new QLabel(); labelC->setFixedSize(100, 25);
    QLabel *labelD = new QLabel(); labelD->setFixedSize(100, 25);

    labelA->setStyleSheet("background-color:blue");
    labelB->setStyleSheet("background-color:yellow");
    labelC->setStyleSheet("background-color:purple");
    labelD->setStyleSheet("background-color:green");

    QGridLayout *layout = new QGridLayout(this);    
    layout->addWidget(labelA, 1, 1); 
    layout->addWidget(labelB, 1, 2);
    layout->addWidget(labelC, 2, 1, 2, 2);
    layout->addWidget(labelD, 3, 1, 3, 2);
}

The result:

enter image description here

Upvotes: 0

Views: 835

Answers (1)

Carthusianorum
Carthusianorum

Reputation: 19

Ok I found the solution (my mistake) :

MyDialogue::MyDialogue(QWidget *parent) : QDialog(parent) {
    QLabel *labelA = new QLabel();
    QLabel *labelB = new QLabel();
    QLabel *labelC = new QLabel();
    QLabel *labelD = new QLabel();

    labelA->setStyleSheet("background-color:blue");
    labelB->setStyleSheet("background-color:yellow");
    labelC->setStyleSheet("background-color:purple");
    labelD->setStyleSheet("background-color:green");

    QGridLayout *layout = new QGridLayout(this);    
    layout->addWidget(labelA, 1, 1); 
    layout->addWidget(labelB, 1, 2);
    layout->addWidget(labelC, 2, 1, 1, 2);
    layout->addWidget(labelD, 3, 1, 1, 2);
}

enter image description here


I was incorrectly thinking that for expanding a row along 2 columns (the case of labelC and labelD) I had to write the corrdinates of the starting cell (2,1) the actual position and then the ending cell (2,2). I was misguided by a Java layout manager that worked exactly that way. Just for the record here you just have to indicate the total number of row span and column span which is 2 in my case.

Upvotes: 1

Related Questions