Home > front end >  Qt how to center widget with a maximum width?
Qt how to center widget with a maximum width?

Time:04-15

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?

CodePudding user response:

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);

CodePudding user response:

The description of the problem is a bit unclear but I will guess the solution: you should try setting the horizontal size policy to Expanding. Then the progress bar will try to get as much space as possible but it will still be limited to that maximum width of 1000 px. Hence:

progressBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

(The vertical policy could remain probably Preferred but you chose Maximum for some reason, so I left it as it was in your code.)

  • Related