File indexing completed on 2024-04-28 05:49:27
0001 /* 0002 * SPDX-FileCopyrightText: 2019 Mark Nauwelaerts <mark.nauwelaerts@gmail.com> 0003 * SPDX-FileCopyrightText: 2022 Waqar Ahmed <waqar.17a@gmail.com>* 0004 * 0005 * SPDX-License-Identifier: MIT 0006 */ 0007 0008 #pragma once 0009 0010 #include <QIcon> 0011 #include <QPainter> 0012 #include <QPixmap> 0013 #include <QStyle> 0014 #include <QStyleOptionViewItem> 0015 #include <QTextLayout> 0016 0017 namespace Utils 0018 { 0019 /** 0020 * @brief colors the @p icon with @fgColor 0021 */ 0022 inline QPixmap colorIcon(const QIcon &icon, const QColor &fgColor, const QSize s = QSize(16, 16)) 0023 { 0024 auto p = icon.pixmap(s); 0025 if (p.isNull()) 0026 return {}; 0027 0028 QPainter paint(&p); 0029 paint.setCompositionMode(QPainter::CompositionMode_SourceIn); 0030 paint.fillRect(p.rect(), fgColor); 0031 paint.end(); 0032 0033 return p; 0034 } 0035 0036 /** 0037 * Draws text in an item view for e.g treeview 0038 * It assumes options.rect == textRect 0039 */ 0040 inline void paintItemViewText(QPainter *p, const QString &text, const QStyleOptionViewItem &options, QList<QTextLayout::FormatRange> formats) 0041 { 0042 // set formats 0043 QTextLayout textLayout(text, options.font); 0044 auto fmts = textLayout.formats(); 0045 formats.append(fmts); 0046 textLayout.setFormats(formats); 0047 0048 // set alignment, rtls etc 0049 QTextOption textOption; 0050 textOption.setTextDirection(options.direction); 0051 textOption.setAlignment(QStyle::visualAlignment(options.direction, options.displayAlignment)); 0052 textLayout.setTextOption(textOption); 0053 0054 // layout the text 0055 textLayout.beginLayout(); 0056 0057 QTextLine line = textLayout.createLine(); 0058 if (!line.isValid()) 0059 return; 0060 0061 const int lineWidth = options.rect.width(); 0062 line.setLineWidth(lineWidth); 0063 line.setPosition(QPointF(0, 0)); 0064 0065 textLayout.endLayout(); 0066 0067 int y = QStyle::alignedRect(Qt::LayoutDirectionAuto, Qt::AlignVCenter, textLayout.boundingRect().size().toSize(), options.rect).y(); 0068 0069 // draw the text 0070 const auto pos = QPointF(options.rect.x(), y); 0071 textLayout.draw(p, pos); 0072 } 0073 0074 } // namespace Utils