PDA

View Full Version : QTableWidget/View resizeColumnsToContents not respected until scroll (PyQt4)



BreakBad
9th April 2013, 16:14
The columns of my table do not resize to contents until you scroll to an item requiring the column be expanded AND resize the splitter pane. Resizing the entire window has the same effect as it also resizes the splitter. My table requires persistent editors, and you will see at row 16 there is a table with 50 columns, which should...after calling 'resizeColumnsToContents' determine the width of column 0. However it will not resize until you scroll down to it and trigger a splitter resize.



from PyQt4 import QtCore,QtGui
import sys

app = QtGui.QApplication(sys.argv)
mw = QtGui.QMainWindow()
spl = QtGui.QSplitter()
spl.addWidget(QtGui.QLabel('Filler'))

# create table
class tbl(QtGui.QTableWidget):
def __init__(self):
super(tbl,self).__init__()
self.setRowCount(20)
self.setColumnCount(2)
self.horizontalHeader().setStretchLastSection(Fals e)
self.horizontalHeader().setResizeMode(QtGui.QHeade rView.ResizeToContents)
self.verticalHeader().setResizeMode(QtGui.QHeaderV iew.ResizeToContents)
self.setItemDelegate(delg(self))

# persist editors
for x in xrange(0,self.rowCount()):
for y in xrange(0,self.columnCount()):
self.setItem(x,y,QtGui.QTableWidgetItem('test'))
for x in xrange(0,self.rowCount()):
for y in xrange(0,self.columnCount()):
self.openPersistentEditor(self.item(x,y))
self.resizeColumnsToContents()

# create item delegate
class delg(QtGui.QItemDelegate):
def __init__(self,parent):
super(delg,self).__init__(parent)

def createEditor(self,parent,option,index):
if index.column() == 1:
return QtGui.QLineEdit(parent=parent)
if index.row() == 15:
t = QtGui.QTableWidget(parent=parent)
t.setRowCount(5)
t.setColumnCount(50)
return t
return QtGui.QLineEdit(parent=parent)

t = tbl()
spl.addWidget(t)
mw.setCentralWidget(spl)

# add and show
mw.show()
sys.exit(app.exec_())


Is there a way to force the table to respect the size of all columns? I have tried overwriting the minimumSizeHint for the editor table but get quirky results, eg: the second column will be painted ontop of the editor table....until I resize the splitter which triggers something....a repaint?

Santosh Reddy
20th April 2013, 19:53
You need to call resizeColumnsToContents() when every QTrewWidget is scrolled, and when every QTreeWidget has items added/removed.