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

时间:2019-01-29 14:13:49

标签: python qt pyqt5 qprogressbar

我正在尝试将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)

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

1 个答案:

答案 0 :(得分:1)

尝试一下:

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

enter image description here