简体   繁体   中英

Qt how to center widget with a maximum width?

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?

Can be fixed by replacing QVBoxLayout with QHBoxLayout and replacing layout->addWidget(progressBar, 0, Qt::AlignCenter); with layout->addWidget(progressBar); progressBar->setAlignment(Qt::AlignCenter); 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM