简体   繁体   中英

How to center align a QPushButton when a QProgressBar is present?

I'm trying to put a QProgressBar below a QPushButton and align them on the center of a QVBoxLayout , but for some reason the button stays left aligned when the progress bar is present and center aligned if it is not.

I tried setting the alignment of all parent widgets and layouts to Qt.AlignCenter , but the progress bar keeps making the button go to the left.

connect_box = QVBoxLayout()
connect_box.setAlignment(Qt.AlignCenter)
connect_button = QPushButton('Connect')
connect_button.setFixedSize(120, 30)
connect_progress = QProgressBar()
connect_progress.setRange(0, 10000)
connect_progress.setValue(0)
connect_box.addWidget(connect_button)
connect_box.addWidget(connect_progress)
connect_box.setContentsMargins(0, 20, 0, 0)

I expect the button to stay center aligned when the progress bar is added.

Try it:

import sys
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

        connect_button = QPushButton('Connect')
        connect_button.setFixedSize(120, 30)

        connect_progress = QProgressBar()
        connect_progress.setRange(0, 10000)
        connect_progress.setValue(0)

        connect_box = QVBoxLayout(self)
        connect_box.setAlignment(Qt.AlignCenter)  

        connect_box.addWidget(connect_button, alignment=Qt.AlignCenter)  # < ----

        connect_box.addWidget(connect_progress)
        connect_box.setContentsMargins(0, 20, 0, 0)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec_())

在此处输入图片说明

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