qlabel centering

aqua boy picture aqua boy · Mar 22, 2012 · Viewed 39.8k times · Source

I have a qlabel L inside a qwidget W. L is vertically and horizontally aligned. When I resize W, L doesn't get centered.

Is this expected? What's a good implementation to have L centered again?

Answer

sgibb picture sgibb · Mar 22, 2012

To align text in a QLabel by calling QLabel::setAlignment works like expected for me.
Maybe you miss to add your Label to a Layout (so your label would automatically resized if your widget is resized). See also Layout Management. A minimal example:

#include <QApplication>
#include <QHBoxLayout>
#include <QLabel>
#include <QWidget>

int main(int argc, char* argv[]) {
    QApplication app(argc, argv);

    QLabel* label=new QLabel("Hello World!");
    label->setAlignment(Qt::AlignCenter);

    QWidget* widget=new QWidget;

    // create horizontal layout
    QHBoxLayout* layout=new QHBoxLayout;
    // and add label to it
    layout->addWidget(label);
    // set layout to widget
    widget->setLayout(layout);

    widget->show();

    return app.exec();
}