在Qt中,当我向布局添加小部件时,默认情况下它们是垂直居中的.有没有办法从上到下"列出"小部件而不是垂直居中?
noi*_*cko 22
我发现这比使用更复杂一些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_()
Run Code Online (Sandbox Code Playgroud)
以下显式调用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_()
Run Code Online (Sandbox Code Playgroud)
col*_*fix 21
如果你有一个QVBoxLayout并希望你的固定大小的小部件堆叠在顶部,你可以简单地添加一个垂直拉伸添加结束:
layout.addStretch()
Run Code Online (Sandbox Code Playgroud)
如果您有多个担架或其他拉伸项,则可以指定一个整数拉伸因子参数来定义它们的大小比例.
另请参见addStretch和addSpacerItem.
不确定这是否回答了你原来的问题,但它是谷歌搜索和引导到这个页面时的答案 - 所以它也可能对其他人有用.
小智 8
在两种解决方案进行比较后,似乎:
myLayout.setAlignment(Qt.AlignTop)
Run Code Online (Sandbox Code Playgroud)
适用于多个小部件对齐但是:
myLayout.setAlignment(myWidget, Qt.AlignTop)
Run Code Online (Sandbox Code Playgroud)
仅适用于添加到布局的第一个窗口小部件.毕竟,解决方案还取决于您的小部件的QSizePolicy.