将QHBoxLayout的每个小部件对齐到顶部 [英] Align every widget of a QHBoxLayout to the top

查看:692
本文介绍了将QHBoxLayout的每个小部件对齐到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将QHBoxlayout中的每个小部件都对齐到顶部,但我得到的是每个小部件似乎都居中。我认为这是由于大小不同所致。

I'm trying to align every widgets in a QHBoxlayout to the top but what I get is every widget seems centered. I think this is due to there different sizes.

例如:

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



class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__()
        self.parent = parent
        self.setFixedWidth(300)
        self.setFixedHeight(100)

        self.wid = QWidget()
        self.setCentralWidget(self.wid)

        self.groups = QHBoxLayout()

        l_a1 = QLabel('A')
        a = QVBoxLayout()
        a.addWidget(l_a1)
        self.groups.addLayout(a)

        l_a2 = QLabel('A')
        l_b2 = QLabel('B')
        a_b = QVBoxLayout()
        a_b.addWidget(l_a2)
        a_b.addWidget(l_b2)
        self.groups.addLayout(a_b)


        l_a3 = QLabel('A')
        l_b3 = QLabel('B')
        l_c3 = QLabel('C')
        a_b_c = QVBoxLayout()
        a_b_c.addWidget(l_a3)
        a_b_c.addWidget(l_b3)
        a_b_c.addWidget(l_c3)
        self.groups.addLayout(a_b_c)

        self.groups.setAlignment(Qt.AlignTop)


        self.wid.setLayout(self.groups)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SurfViewer(app)
    ex.setWindowTitle('window')
    ex.show()
    sys.exit(app.exec_( ))

我得到了:

我想要的是类似的东西:

what I would like instead is something like :

推荐答案

您必须将对齐方式应用于每种布局:

You must apply the alignment to each layout:

class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__(parent=parent)
        self.setFixedSize(300, 100)

        self.wid = QWidget()
        self.setCentralWidget(self.wid)

        self.groups = QHBoxLayout(self.wid)

        l_a1 = QLabel('A')
        a = QVBoxLayout()
        a.addWidget(l_a1)

        l_a2 = QLabel('A')
        l_b2 = QLabel('B')
        a_b = QVBoxLayout()
        a_b.addWidget(l_a2)
        a_b.addWidget(l_b2)

        l_a3 = QLabel('A')
        l_b3 = QLabel('B')
        l_c3 = QLabel('C')
        a_b_c = QVBoxLayout()
        a_b_c.addWidget(l_a3)
        a_b_c.addWidget(l_b3)
        a_b_c.addWidget(l_c3)

        a.setAlignment(Qt.AlignTop)
        a_b.setAlignment(Qt.AlignTop)
        a_b_c.setAlignment(Qt.AlignTop)

        self.groups.addLayout(a)
        self.groups.addLayout(a_b)
        self.groups.addLayout(a_b_c)
        self.groups.setAlignment(Qt.AlignTop)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SurfViewer()
    ex.setWindowTitle('window')
    ex.show()
    sys.exit(app.exec_( ))

这篇关于将QHBoxLayout的每个小部件对齐到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆