python - 自动调整Widget高度

标签 python qt pyqt

我想知道如何创建一个小部件,当我编辑包含该小部件的 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/

相关文章:

python - Python 中的 UDP 套接字 : How to clear the buffer and ignore oldes messages

c++ - 创建元素为数组的堆栈

unit-testing - QT:获取对象的类名

python - 如何使用 QAbstractItemModel 从 QTreeView 中删除行?

python - 将项目添加到已填充的组合框中

python - 禁用 QDial 鼠标点击和换针

python - 即使存在 301 状态,如何获取响应文本?

python - Pandas 如何根据一列中的值在多行中添加值

python - 从另一个子目录访问文件

PyQt QGraphicsView 使用变换矩阵进行平移和缩放