调整QVBoxLayout的大小

时间:2013-01-26 16:31:58

标签: python qt pyqt pyqt4 pyside

我有一个QVBoxLayout,我放了一些按钮。我写了一个删除按钮的功能,但是当我这样做时,该框不会使其大小适应内容。 这是删除功能的一部分:

for each_difference in differences_remove:

    old_index = self.all_tags.index(each_difference) 
    print("old" + str(old_index))
    self.vbox_all_tags.removeWidget(self.liste_pressoirs[old_index])
    del self.liste_pressoirs[old_index]

我希望self.vbox_all_tags在删除按钮后调整其大小以适应新内容。你会怎么做?

1 个答案:

答案 0 :(得分:1)

删除按钮后,只需在您的小部件上调用adjustSize,这是一个演示:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui

class MyWindow(QtGui.QWidget):
    _buttons = []

    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonRemove = QtGui.QPushButton(self)
        self.pushButtonRemove.setText("Remove A Button!")
        self.pushButtonRemove.clicked.connect(self.on_pushButtonRemove_clicked)

        self.widgetButtons = QtGui.QWidget(self)

        self.layoutButtons = QtGui.QHBoxLayout(self.widgetButtons)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.pushButtonRemove)
        self.layout.addWidget(self.widgetButtons)

        for buttonNumber in range(3):
            pushButton = QtGui.QPushButton()
            pushButton.setText("Button {0}".format(buttonNumber))

            self._buttons.append(pushButton)
            self.layoutButtons.addWidget(pushButton)

    @QtCore.pyqtSlot()
    def on_pushButtonRemove_clicked(self):
        if self._buttons:
            pushButton = self._buttons[-1]

            self._buttons.pop()
            self.layoutButtons.removeWidget(pushButton)

            pushButton.deleteLater()

            self.widgetButtons.adjustSize()
            self.adjustSize()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())