存在 QProgressBar 时如何居中对齐 QPushButton?

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

我试图将 QProgressBar 放在 QPushButton 下方,并将它们对齐到 QVBoxLayout 的中心,但由于某些原因,按钮在进行时保持左对齐条形图存在并且居中对齐(如果不存在)。

我尝试将所有父控件和布局的对齐方式设置为 Qt.AlignCenter,但进度条一直让按钮向左移动。

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)

我希望按钮在添加进度条时保持居中对齐。

试一试:

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_())