I have the following function to be able to resize the first two columns of a table in PySide6 while keeping the third the same size since it contains a combobox and keeps the ratios they get of the table widget rectangle even if i make the size of the whole program bigger or smaller
def auto_n_manual_resize(self):
self.header.setStretchLastSection(False)
widget_width = self.wordsTable.contentsRect().width()
column0 = self.header.sectionSize(0)
column1 = self.header.sectionSize(1)
scroll = self.wordsTable.verticalScrollBar().sizeHint().width()
verHeadWidth = self.wordsTable.verticalHeader().sizeHint().width()
available_width = (
widget_width - verHeadWidth - scroll - 90
) # the 3rd col should be 90 pix wide
denom = column0 + column1 or 1
if denom == 0:
column0 = column1 = 1
denom = 2
col0_W_per = column0 / denom
col1_W_per = column1 / denom
newCol0Width = int(col0_W_per * available_width)
newcol1Width = int(col1_W_per * available_width)
self.header.sectionResized.disconnect(self.auto_n_manual_resize)
self.wordsTable.setColumnWidth(0, newCol0Width)
self.wordsTable.setColumnWidth(1, newcol1Width)
self.wordsTable.setColumnWidth(2, 90)
self.header.sectionResized.connect(self.auto_n_manual_resize)
self.header.setMinimumSectionSize(60)
self.header.setMaximumSectionSize((available_width))
self.header.setStretchLastSection(True)
the code works "perfectly" as far as I can see, but i get this warning when I run the program
RuntimeWarning: Failed to disconnect (<bound method Table.auto_n_manual_resize of <widgets.Table(0x20d074122a0) at 0x0000020D07ADD280>>) from signal "sectionResized(int,int,int)".
which is the weird part cause before I placed the disconnect and connect methods when I resized the columns they weren't constrained to the visible rectangle of the table but would immediately expand beyond and I would get a horizontal scrollbar but then would snap back to the visible rectangle of the table when i resized the whole window of the program, so it essence it works but I get this warning and I don't know what to do
setStretchLastSection(), which will trigger againsectionResized. In cases like these, where the connected function potentially causes itself to be called again, it's normally better to use an internal "flag" that needs to be checked before doing anything. Try setting a class attribute (eg:_recursionCheck = False), then at the beginning of the function addif self._recursionCheck: return, followed byself._recursionCheck = Truebefore the rest of the function, and concluding it withself._recursionCheck = False.