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)
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__":
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_())
To copy to clipboard, switch view to plain text mode
Bookmarks