AlexVhr
12th April 2013, 17:15
Hi! I've a usual TableView-TableModel-Delegate setup, and use Delegate.sizeHint() to control column width. It works perfectly, but only when my model has rows. If it's empty, then columns have default width, which is not good. What can be the couse of it? Full test case follows (python):
import sys
from PySide import QtGui, QtCore
class Person:
def __init__(self, f_name, l_name, country):
self.f_name = f_name
self.l_name = l_name
self.country = country
class MyDelegate(QtGui.QStyledItemDelegate):
def sizeHint(self, option, index):
super().sizeHint(option, index)
width = index.model().sizes[index.column()]
return QtCore.QSize(width, 24)
class MyModel(QtCore.QAbstractTableModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.columns = ['f_name','l_name', 'country']
self.sizes = [70, 70, 35]
self.rows = [Person('John', 'Doe', 'USA'),
Person('Hans', 'Mann', 'DE')]
#self.rows = [] #uncomment this to see it fail
def rowCount(self, *args, **kwargs):
return len(self.rows)
def columnCount(self, *args, **kwargs):
return len(self.columns)
def data(self, index, role):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
row = self.rows[index.row()]
col = self.columns[index.column()]
attr = getattr(row, col)
return attr
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win = QtGui.QTableView()
win.setModel(MyModel())
win.setItemDelegate(MyDelegate(win))
win.resizeColumnsToContents()
win.show()
sys.exit(app.exec_())
import sys
from PySide import QtGui, QtCore
class Person:
def __init__(self, f_name, l_name, country):
self.f_name = f_name
self.l_name = l_name
self.country = country
class MyDelegate(QtGui.QStyledItemDelegate):
def sizeHint(self, option, index):
super().sizeHint(option, index)
width = index.model().sizes[index.column()]
return QtCore.QSize(width, 24)
class MyModel(QtCore.QAbstractTableModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.columns = ['f_name','l_name', 'country']
self.sizes = [70, 70, 35]
self.rows = [Person('John', 'Doe', 'USA'),
Person('Hans', 'Mann', 'DE')]
#self.rows = [] #uncomment this to see it fail
def rowCount(self, *args, **kwargs):
return len(self.rows)
def columnCount(self, *args, **kwargs):
return len(self.columns)
def data(self, index, role):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
row = self.rows[index.row()]
col = self.columns[index.column()]
attr = getattr(row, col)
return attr
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win = QtGui.QTableView()
win.setModel(MyModel())
win.setItemDelegate(MyDelegate(win))
win.resizeColumnsToContents()
win.show()
sys.exit(app.exec_())