Aligning qlabel text in centre
-
I am trying to create a label on which I can display my image and above it a qlabel text for saying this is my input image and then setting both of them in vertical layout. But text always gets allign to the left. I also tried allign the text at the centre and then apply vertical layout but doesn't work. I am using Qt designer.
I also used horizontal spacer with qlabel text and set them to horizontal layout, then adding horizontal layout and image display label in vertical layout but nothing seems to work.Is there any better way to do that.
-
Are you setting the alignment on the label or on the layout? It should be on the label.
Here's an example: -
@Sumit ,
Widget::Widget(QWidget *parent) : QWidget(parent) { m_ImageLabel = new QLabel; m_TextLabel = new QLabel; m_VLayout = new QVBoxLayout; QPixmap pixmap("Image.png"); m_ImageLabel->setPixmap(pixmap); m_TextLabel->setText("Text"); m_VLayout->addWidget(m_TextLabel,Qt::AlignCenter); m_VLayout->addWidget(m_ImageLabel,Qt::AlignCenter); this->setLayout(m_VLayout); }
-
@Sumit ,
Widget::Widget(QWidget *parent) : QWidget(parent) { m_ImageLabel = new QLabel; m_TextLabel = new QLabel; m_VLayout = new QVBoxLayout; QPixmap pixmap("Image.png"); m_ImageLabel->setPixmap(pixmap); m_TextLabel->setText("Text"); m_VLayout->addWidget(m_TextLabel,Qt::AlignCenter); m_VLayout->addWidget(m_ImageLabel,Qt::AlignCenter); this->setLayout(m_VLayout); }
@Vinod-Kuntoji That's not gonna work. This code aligns the label itself to the horizontal center of the layout, but since neither of the labels have maximum size constraints they will both occupy the same amount of space, filling the layout, so this alignment doesn't matter.
What you need to do is align the text inside the label, not the label itself i.e.m_TextLabel->setAlignment(Qt::AlignCenter)
. -
Hi,
@Sumit ,
u can use as mentioned by @Chris-Kawa , to align text in middle of QLabel,
m_label->setStyleSheet("background-color:red;"); m_label->setText("Qt QML"); m_label->setAlignment(Qt::AlignCenter);
This may help u ,
Thanks,
-
Are you setting the alignment on the label or on the layout? It should be on the label.
Here's an example:@Chris-Kawa yes i do it on label only, but when I put them in vertical layout it moves to left.
-
Are you setting the alignment on the label or on the layout? It should be on the label.
Here's an example:@Chris-Kawa I got the mistake, I was keeping size policy fixed due to which allignment has no effect on the text label.
Thank you everyone. It got solved
-
@Sumit ,
Widget::Widget(QWidget *parent) : QWidget(parent) { m_ImageLabel = new QLabel; m_TextLabel = new QLabel; m_VLayout = new QVBoxLayout; QPixmap pixmap("Image.png"); m_ImageLabel->setPixmap(pixmap); m_TextLabel->setText("Text"); m_VLayout->addWidget(m_TextLabel,Qt::AlignCenter); m_VLayout->addWidget(m_ImageLabel,Qt::AlignCenter); this->setLayout(m_VLayout); }
@Vinod-Kuntoji nice example, thank you!