PyQt4 QVBoxLayout.addStretch()在不需要时添加不需要的空格

时间:2015-04-07 21:33:27

标签: python qt pyqt4

我遇到一些问题,PyQt4的表现并不理想。

我有一个搜索框,下面的列表以及搜索框和列表右侧的可选图片。

没有拉伸间隔物,物品将获得它们之间的所有多余空间。

问题在于,当我添加一个弹力项时,如果列表中没有任何内容,则占用的空间比需要的多,在窗口中添加了多余的空白区域。

这是一个证明问题的最小例子

#!/usr/bin/python
# -*- coding: utf8 -*-

import sys

from PyQt4 import QtGui, QtCore

class SearchTool(QtGui.QWidget):
    def __init__(self):
        super(SearchTool, self).__init__()
        self.initUI()

    def initUI(self):
        self.searchField = QtGui.QLineEdit()

        self.gui_0 = QtGui.QVBoxLayout()

        self.gui_0.addWidget(self.searchField)

        # Comment out the following line to see desired output.
        self.gui_0.addStretch()

        self.setLayout(self.gui_0)
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = SearchTool()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

使用.addStretch()
with stretch

没有.addStretch()
without stretch
这就是我想要的样子。

伸展的原因

只是列表,此项目没有图片。
List without picture and stretch

列表和图片,没有拉伸。
List with picture, without stretch

列表和图片,有拉伸。
List with picture, with stretch
这就是我想要的样子。

2 个答案:

答案 0 :(得分:0)

作为解决方法,在显示窗口后添加拉伸:

self.show()
self.gui_0.addStretch()

答案 1 :(得分:0)

我不知道这是否是正确的"解决方案,但似乎你只需将窗口的高度调整为一个小值,然后布局将自动重新扩展到所需的最小高度:

    self.setLayout(self.gui_0)
    self.adjustSize()
    self.resize(self.width(), 1)
    self.show()

但我仍然不明白为什么布局是用冗余间隔器初始化的......