2012-04-10 105 views

回答

28

使用void QLayout::setAlignment (Qt::Alignment alignment)方法根据您的选择设置对齐方式。

14

我觉得这比使用layout.setAlignment()稍微复杂一些。直到现在,我一直在为我工作,当我发现如果你扩展了你设置的最大高度的小部件,那么这个小部件将不会按照你想要的方式排列。

下面是代码示例不是顶部对齐QTextBrowser()小部件,即使我打电话layout.setAlignment(Qt.AlignTop)。对不起,它是在Python中,但它很容易转换为C++(我已经多次走了另一条路)。

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

class MyWidget(QWidget): 
    """ 
    Create a widget that aligns its contents to the top. 
    """ 

    def __init__(self, parent=None): 

     QWidget.__init__(self, parent) 

     layout = QVBoxLayout() 

     label = QLabel('label:') 
     layout.addWidget(label) 

     info = QTextBrowser(self) 
     info.setMinimumHeight(100) 
     info.setMaximumHeight(200) 
     layout.addWidget(info)   
     # Uncomment the next line to get this to align top. 
#   layout.setAlignment(info, Qt.AlignTop) 

     # Create a progress bar layout. 
     button = QPushButton('Button 1')   
     layout.addWidget(button)   

     # This will align all the widgets to the top except 
     # for the QTextBrowser() since it has a maximum size set. 
     layout.setAlignment(Qt.AlignTop) 

     self.setLayout(layout) 


if __name__ == '__main__': 

    import sys 

    app = QApplication(sys.argv) 

    widget = MyWidget() 
    widget.show() 
    widget.resize(QSize(900, 400)) 

    app.exec_() 

以下显式调用layout.setAlignment(info, Qt.AlignTop)以使扩展文本小部件工作。

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

class MyWidget(QWidget): 
    """ 
    Create a widget that aligns its contents to the top. 
    """ 

    def __init__(self, parent=None): 

     QWidget.__init__(self, parent) 

     layout = QVBoxLayout() 

     label = QLabel('label:') 
     layout.addWidget(label) 

     info = QTextBrowser(self) 
     info.setMinimumHeight(100) 
     info.setMaximumHeight(200) 
     layout.addWidget(info)   
     # Uncomment the next line to get this to align top. 
     layout.setAlignment(info, Qt.AlignTop) 

     # Create a progress bar layout. 
     button = QPushButton('Button 1')   
     layout.addWidget(button)   

     # This will align all the widgets to the top except 
     # for the QTextBrowser() since it has a maximum size set. 
     layout.setAlignment(Qt.AlignTop) 

     self.setLayout(layout) 


if __name__ == '__main__': 

    import sys 

    app = QApplication(sys.argv) 

    widget = MyWidget() 
    widget.show() 
    widget.resize(QSize(900, 400)) 

    app.exec_() 
+0

这也解决了我的问题。我不确定*为什么*需要设置最小宽度/高度。你可能会解释一下吗? – Seth 2015-05-07 04:08:54

4

两个解决方案比较后,似乎:

myLayout.setAlignment(Qt.AlignTop) 

作品数部件alignement但:

myLayout.setAlignment(myWidget, Qt.AlignTop) 

仅适用于第一控件添加到布局。 毕竟,解决方案也依赖于你的widget的QSizePolicy。

4

如果你有一个QVBoxLayout,并希望自己的固定大小的小部件在顶部堆叠,你可以简单地追加一个垂直拉伸添加结束:

layout.addStretch() 

如果您有多个担架或其它拉伸物品,您可以指定一个整数伸展因子参数来定义它们的大小比例。请参阅addStretchaddSpacerItem

不确定这是否回答您的原始问题,但它是我在Google上搜索并引导到此​​页面时所回答的问题的答案 - 因此它可能对其他人有用。

+0

有没有办法给帖子添加500个大拇指? – Acidic 2018-02-08 04:40:30