Debian Codegraph @

avogadro/qtgui/richtextdelegate.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "richtextdelegate.h"
7
8 #include <cmath>
9
10 namespace Avogadro::QtGui {
11
12 // See for example
13 // https://gist.github.com/jniemann66/dbc298b35a840bf3f1a2206ea6284c7b
14 // and https://stackoverflow.com/a/66412883/131896
15
16 RichTextDelegate::RichTextDelegate(QObject* parent_)
17 : QStyledItemDelegate(parent_)
18 {
19 }
20
21 RichTextDelegate::~RichTextDelegate(){};
22
23 QSize RichTextDelegate::sizeHint(const QStyleOptionViewItem& o,
24 const QModelIndex& index) const
25 {
26 QStyleOptionViewItem ov = o;
27 initStyleOption(&ov, index);
28
29 // Check after initStyleOption populates ov.text from the model
30 if (ov.text.isEmpty()) {
31 return QStyledItemDelegate::sizeHint(o, index);
32 }
33
34 QTextDocument doc;
35 doc.setHtml(ov.text);
36 doc.setTextWidth(ov.rect.width());
37 doc.setDefaultFont(ov.font);
38
39 return QSize(std::ceil(doc.idealWidth()), std::ceil(doc.size().height()));
40 }
41
42 void RichTextDelegate::paint(QPainter* p, const QStyleOptionViewItem& o,
43 const QModelIndex& index) const
44 {
45 QStyleOptionViewItem ov = o;
46 initStyleOption(&ov, index);
47
48 p->save();
49
50 QTextDocument doc;
51 doc.setHtml(ov.text);
52 doc.setDefaultFont(ov.font);
53
54 ov.text = "";
55 ov.widget->style()->drawControl(QStyle::CE_ItemViewItem, &ov, p);
56
57 // Calculate position based on alignment
58 QSizeF docSize = doc.size();
59 qreal x = ov.rect.left();
60 qreal y = ov.rect.top();
61
62 // Get alignment from the style option (populated from Qt::TextAlignmentRole)
63 Qt::Alignment alignment = ov.displayAlignment;
64
65 // Horizontal alignment
66 if (alignment & Qt::AlignHCenter) {
67 x += (ov.rect.width() - docSize.width()) / 2.0;
68 } else if (alignment & Qt::AlignRight) {
69 x += ov.rect.width() - docSize.width();
70 }
71
72 // Vertical alignment
73 if (alignment & Qt::AlignVCenter) {
74 y += (ov.rect.height() - docSize.height()) / 2.0;
75 } else if (alignment & Qt::AlignBottom) {
76 y += ov.rect.height() - docSize.height();
77 }
78
79 p->translate(x, y);
80 QRect clip(0, 0, ov.rect.width(), ov.rect.height());
81 doc.drawContents(p, clip);
82 p->restore();
83 }
84
85 } // namespace Avogadro::QtGui