18

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?

aqua boy
  • 379
  • 2
  • 3
  • 7

1 Answers1

32

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();
}
sgibb
  • 23,631
  • 1
  • 59
  • 67