我想知道如何创建一个小部件,当我编辑包含该小部件的 QDialog 的高度时,该小部件会自动适应空间。
在下面的示例中,QPushButton 将适合 QDialog 的宽度,但不适合高度。但是,如果我创建 QTextEdit 而不是 QPushButton,则 QTextEdit 将完美适合 QDialog。
from PySide.QtGui import *
class c (QDialog):
def __init__(self):
QDialog.__init__(self)
self.setLayout(QVBoxLayout())
self.layout().setSpacing (0)
self.layout().setContentsMargins(0,0,0,0);
btn = QPushButton()
self.layout().addWidget(btn)
self.exec_()
a = c()
最佳答案
The C++ documentation of the QBoxLayout Class状态为
QBoxLayout::addWidget(widget, stretch=0, alignment=0)
If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of each widget that's involved.
所以看看默认的 Policy
QPushButton
>>> btn = QPushButton()
>>> btn.sizePolicy().horizontalPolicy()
1
>>> btn.sizePolicy().verticalPolicy()
0
我们会发现,垂直策略是固定的。添加按钮如
[...]
btn = QPushButton()
policy = btn.sizePolicy().horizontalPolicy()
btn.setSizePolicy(policy, policy)
self.layout().addWidget(btn)
[...]
现在将自动调整对话框中的按钮。
关于python - 自动调整Widget高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31327815/