Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qlabel centering

Tags:

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?

like image 529
aqua boy Avatar asked Mar 22 '12 05:03

aqua boy


1 Answers

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();
}
like image 194
sgibb Avatar answered Oct 29 '22 23:10

sgibb