Reputation: 19329
Unfortunately QTableView.resizeRowsToContents()
sets the height of only those rows (or items) that are currently populating the TableView
. With a first model
's reset() or update the QTableView
's row's heights switch back to some default value (which seems to be around 32 px high).
Most of the time this default row height is unnecessarily high leaving a lot of valuable screen space unfilled.
How to apply the change to the row height permanently?
Upvotes: 3
Views: 2997
Reputation: 191
I found out two ways to permanently set the rows height, you either have to use SizeHintRole in your model or implement the sizeHint method in a QStyledItemDelegate. Here's what the code will look like:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class ListModel(QAbstractListModel):
def __init__(self, data=[], parent=None):
QAbstractListModel.__init__(self, parent)
self.data = data
def rowCount(self, parent=None):
return len(self.data)
def data(self, index, role=None):
if role == Qt.DisplayRole:
row = index.row()
value = self.data[row]
return value
# ==============Comment if you're using delegate===============
if role == Qt.SizeHintRole:
return QSize(100, 75)
# =============================================================
class ListDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
QStyledItemDelegate.__init__(self, parent)
def sizeHint(self, option, index):
return QSize(100, 20)
app = QApplication(sys.argv)
listview = QListView()
model = ListModel([12, 15, 19])
listview.setModel(model)
# =============uncomment to use delegate=====================
# delegate = ListDelegate()
# listview.setItemDelegate(delegate)
# ============================================================
listview.show()
sys.exit(app.exec_())
Upvotes: 3