Reputation: 781
I have a QTableView in my GUI in which I want to have some table cells in which I can insert line breaks using something like \n
or <br>
.
So far I have tried to set an QLabel as the IndexWidget:
l = QLabel(val[2])
self.setRowHeight(i, int(l.height() / 8))
l.setAutoFillBackground(True)
self.setIndexWidget(QAbstractItemModel.createIndex(self.results_model, i, 2), l)
The Problem with this approach is the code is not very clean and cannot just be done in the AbstractTableModel without this code to replace the cell with a widget. The second problem is, that when selecting a row with a widget in it the blue highlighting doesn't apply to the cell. Another problem is that the resizeRowsToContents() method doesn't take the height of this widget in to consideration.
Any Ideas would be very appreciated, thanks!
Upvotes: 1
Views: 2077
Reputation: 243897
One way to implement this task is to use an HtmlDelegate, in this case the line break will be given by <br>
:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class HTMLDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
painter.save()
doc = QTextDocument()
doc.setHtml(opt.text)
opt.text = "";
style = opt.widget.style() if opt.widget else QApplication.style()
style.drawControl(QStyle.CE_ItemViewItem, opt, painter)
painter.translate(opt.rect.left(), opt.rect.top())
clip = QRectF(0, 0, opt.rect.width(), opt.rect.height())
doc.drawContents(painter, clip)
painter.restore()
def sizeHint(self, option, index ):
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
doc = QTextDocument()
doc.setHtml(opt.text);
doc.setTextWidth(opt.rect.width())
return QSize(doc.idealWidth(), doc.size().height())
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QTableView()
model = QStandardItemModel(4, 6)
delegate = HTMLDelegate()
w.setItemDelegate(delegate)
w.setModel(model)
w.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
w.show()
sys.exit(app.exec_())
Upvotes: 4