窗口小部件水平居中,并标记在这些窗口小部件的左侧

时间:2017-04-22 10:51:39

标签: python pyqt

有些小工具水平居中:

class TestWidget(QWidget):

    def __init__(self):
        super().__init__()
        self._init_ui()

    def _init_ui(self):
        edit1_label = QLabel("Edit1")
        edit2_label = QLabel("Edit2")
        edit3_label = QLabel("Edit3")
        edit1 = QLineEdit()
        edit2 = QLineEdit()
        edit3 = QLineEdit()

        layout = QVBoxLayout()
        layout.addWidget(edit1)
        layout.addWidget(edit2)
        layout.addWidget(edit3)
        layout.addStretch()

        hlayout = QHBoxLayout()
        hlayout.addLayout(layout)
        self.setLayout(hlayout)
        self.setAttribute(Qt.WA_StyledBackground)


def _main():
    app = QApplication([''])
    app.setStyleSheet("""
                    TestWidget {
                        min-height: 400px;
                        max-height: 400px;
                        min-width: 600px;
                        max-width: 600px;
                    }
                    TestWidget QLineEdit {
                        min-height: 2em;
                        max-height: 2em;
                        min-width: 20em;
                        max-width: 20em;
                        }
                    """)
w = TestWidget()
w.show()
app.exec_()

我想在编辑的左侧放置标签(edit1_label,edit2_label,edit3_label)(edit1,edit2,edit3)。但是编辑应该在表格上水平居中。怎么可以实现?

更新:添加了示例图形(请注意QLineEdits在表单上水平居中):

example graphic

错误的结果: enter image description here

1 个答案:

答案 0 :(得分:1)

我不确定这是否是您想要的,但它可能有所帮助:

def _init_ui(self):
    mainLayout = QGridLayout()
    mainLayout.setColumnStretch(0, 1)
    mainLayout.setColumnStretch(3, 1)

    edit1_label = QLabel("Edit1")
    edit1 = QLineEdit()

    mainLayout.addWidget(edit1_label, 1, 1)
    mainLayout.addWidget(edit1, 1, 2)

    edit2_label = QLabel("Edit2")
    edit2 = QLineEdit()

    mainLayout.addWidget(edit2_label, 2, 1)
    mainLayout.addWidget(edit2, 2, 2)

    edit3_label = QLabel("Edit3")
    edit3 = QLineEdit()

    mainLayout.addWidget(edit3_label, 3, 1)
    mainLayout.addWidget(edit3, 3, 2)

    mainLayout.setAlignment(Qt.AlignTop)

    self.setLayout(mainLayout)
    self.setAttribute(Qt.WA_StyledBackground)