Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a QLabel to expand to full width?

Tags:

c++

qt

I want a QLabel to expand to full width of the container regardless of the contents. (I want this because I dynamically set the text and add widgets later which cause it to cut off part of the text)

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    this->setFixedSize(100,100);
    QHBoxLayout *layout = new QHBoxLayout;
    this->setLayout(layout);
    QLabel *label = new QLabel;
    label->setStyleSheet("background-color:blue");
    label->setSizePolicy(QSizePolicy::MinimumExpanding, 
                         QSizePolicy::MinimumExpanding);
    label->setText(tr("test"));
    layout->addWidget(label, 0, Qt::AlignTop | Qt::AlignLeft);
}

This code shows that the blue box does not expand to the entire width, why?

like image 322
chacham15 Avatar asked Dec 21 '12 17:12

chacham15


1 Answers

You must set:

layout->setContentsMargins(0,0,0,0);

By default every QWidget or QFrame add 15 pixels of margin in every direction.

The main problem is with setting the alignment when you add the widget to the layout. Use label->setAlignment instead.

layout->addWidget(label);

I compiled your code, it works with those changes.

Here is the minimal example:

#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget* w = new QWidget;
    w->setFixedSize(100,100);
    QHBoxLayout* layout = new QHBoxLayout;
    layout->setContentsMargins(0,0,0,0);
    w->setLayout(layout);
    QLabel* label = new QLabel;
    label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    label->setContentsMargins(0,0,0,0);
    label->setStyleSheet("background-color:blue");
    label->setSizePolicy(QSizePolicy::MinimumExpanding,
                     QSizePolicy::MinimumExpanding);
    label->setText("test");
    layout->addWidget(label);
    w->show();
    return a.exec();
}
like image 90
Kirell Avatar answered Sep 28 '22 01:09

Kirell