Qt how to center widget with a maximum width?

441 Views Asked by At

How can I horizontally center a widget in Qt, in such a way that it stretches out up to a certain size? I tried the following:

QVBoxLayout *layout = new QVBoxLayout(this);
QProgressBar *progressBar = new QProgressBar();
progressBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
progressBar->setMaximumWidth(1000);
layout->addWidget(progressBar, 0, Qt::AlignCenter);

However, the progress bar is always smaller than 1000px. How could I make it to stretch to 1000px, but shrink if the parent widget is smaller and center it at the same time?

1

There are 1 best solutions below

0
On BEST ANSWER

Can be fixed by replacing QVBoxLayout with QHBoxLayout and replacing layout->addWidget(progressBar, 0, Qt::AlignCenter); with layout->addWidget(progressBar); progressBar->setAlignment(Qt::AlignCenter);, guess these two alignments are different.

QHBoxLayout *layout = new QHBoxLayout(this);
QProgressBar *progressBar = new QProgressBar();
progressBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
progressBar->setMaximumWidth(1000);
progressBar->setAlignment(Qt::AlignCenter);
layout->addWidget(progressBar);