1

I have a QVBoxLayout where I put some buttons. I wrote a function to remove a button, but when I do it, the box doesn't adapt its size to the content. Here is a piece of the removal function:

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]

I would like self.vbox_all_tags to adapt its size to the new content after I remove a button. How would you do that ?

Kindly.

4

1 回答 1

2

删除按钮后只需调用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_())
于 2013-01-26T17:31:50.747 回答