2012-04-10 104 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