在添加小部件后,没有一种方法可以重置行或列跨度。但是,可以再次对同一小部件调用addWidget
以实现相同的效果,因为将小部件重新添加到同一布局中始终会隐式地首先将其删除。因此,以下内容应该可行:
index = layout.indexOf(widget)
row, column = layout.getItemPosition(index)[:2]
layout.addWidget(widget, row, column, rowspan, colspan)
这里是一个简单的演示脚本:
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_())