pythonpyqtpyqt5qgridlayoutcolumnspan

How to reset the column span of a widget in a QGridLayout?


Is possible to set the column span of a QLineEdit box after it has been added to the layout? I have two QLineEdit boxes in a QGridLayout that are right next to each other horizontally. During the execution of some of my code, one of these boxes gets hidden. I would like to increase the column span where the hidden one was to avoid a weird gap at the end, and reduce it when needed.

I couldn't really find anything in the Qt documentation for this type of change beyond making the adjustment prior to adding the widget to the layout.


Solution

  • There no method for resetting the row- or column-span after a widget has been added. However, addWidget can be called again on the same widget to achieve the same affect, because re-adding a widget to the same layout always implicitly removes it first. So something like this should work:

    index = layout.indexOf(widget)
    row, column = layout.getItemPosition(index)[:2]
    layout.addWidget(widget, row, column, rowspan, colspan)
    

    Here is a simple demo script:

    import sys
    from PyQt5 import QtCore, QtWidgets
    
    class Window(QtWidgets.QWidget):
        def __init__(self):
            super(Window, self).__init__()
            self.button = QtWidgets.QPushButton('Toggle Edit')
            self.button.clicked.connect(self.handleButton)
            self.edit1 = QtWidgets.QLineEdit()
            self.edit1.setPlaceholderText('One')
            self.edit2 = QtWidgets.QLineEdit()
            self.edit2.setPlaceholderText('Two')
            layout = QtWidgets.QGridLayout(self)
            layout.addWidget(self.edit1, 0, 0)
            layout.addWidget(self.edit2, 0, 1)
            layout.addWidget(self.button, 1, 0)
    
        def handleButton(self):
            if self.edit2.isHidden():
                self.setWidgetSpan(self.edit1, 1, 1)
                self.edit2.setHidden(False)
            else:
                self.edit2.setHidden(True)
                self.setWidgetSpan(self.edit1, 1, 2)
    
        def setWidgetSpan(self, widget, rowspan=1, colspan=1):
            layout = self.layout()
            index = layout.indexOf(widget)
            row, column = layout.getItemPosition(index)[:2]
            layout.addWidget(widget, row, column, rowspan, colspan)
    
    if __name__ == '__main__':
    
        app = QtWidgets.QApplication(sys.argv)
        window = Window()
        window.setGeometry(600, 100, 300, 100)
        window.show()
        sys.exit(app.exec_())