File indexing completed on 2024-10-06 06:47:25
0001 /* 0002 This file is part of Killbots. 0003 0004 SPDX-FileCopyrightText: 2007-2009 Parker Coates <coates@kde.org> 0005 0006 SPDX-License-Identifier: GPL-2.0-or-later 0007 */ 0008 0009 #include "numericdisplayitem.h" 0010 0011 #include "renderer.h" 0012 0013 #include <QFontMetrics> 0014 #include <QPainter> 0015 0016 Killbots::NumericDisplayItem::NumericDisplayItem(const QString &label, QGraphicsItem *parent) 0017 : QObject(), 0018 KGameRenderedItem(Renderer::self(), QStringLiteral("status"), parent), 0019 m_label(label), 0020 m_value(0), 0021 m_digits(3) 0022 { 0023 setShapeMode(QGraphicsPixmapItem::BoundingRectShape); 0024 setFont(QFont()); 0025 setRenderSize(preferredSize()); 0026 } 0027 0028 Killbots::NumericDisplayItem::~NumericDisplayItem() 0029 { 0030 } 0031 0032 int Killbots::NumericDisplayItem::value() const 0033 { 0034 return m_value; 0035 } 0036 0037 QString Killbots::NumericDisplayItem::label() const 0038 { 0039 return m_label; 0040 } 0041 0042 int Killbots::NumericDisplayItem::digits() const 0043 { 0044 return m_digits; 0045 } 0046 0047 QFont Killbots::NumericDisplayItem::font() const 0048 { 0049 return m_font; 0050 } 0051 0052 QSize Killbots::NumericDisplayItem::preferredSize() 0053 { 0054 QSize labelSize = QFontMetrics(m_font).boundingRect(m_label).size(); 0055 QSize digitsSize = QFontMetrics(m_boldFont).boundingRect(QString(m_digits + 1, QLatin1Char('8'))).size(); 0056 0057 return QSize(labelSize.width() + digitsSize.width() + 2 * m_margin, 0058 qMax(labelSize.height(), digitsSize.height()) + 2 * m_margin 0059 ); 0060 } 0061 0062 void Killbots::NumericDisplayItem::paint(QPainter *p, const QStyleOptionGraphicsItem *option, QWidget *widget) 0063 { 0064 KGameRenderedItem::paint(p, option, widget); 0065 0066 p->save(); 0067 0068 QRectF textRect = boundingRect().adjusted(m_margin, m_margin, -m_margin, -m_margin); 0069 p->setPen(Renderer::self()->textColor()); 0070 0071 p->setFont(m_font); 0072 p->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, m_label); 0073 0074 p->setFont(m_boldFont); 0075 p->drawText(textRect, Qt::AlignRight | Qt::AlignVCenter | Qt::TextSingleLine, QString::number(m_value)); 0076 0077 p->restore(); 0078 } 0079 0080 void Killbots::NumericDisplayItem::setValue(int value) 0081 { 0082 if (value != m_value) { 0083 m_value = value; 0084 update(); 0085 } 0086 } 0087 0088 void Killbots::NumericDisplayItem::setLabel(const QString &label) 0089 { 0090 if (label != m_label) { 0091 m_label = label; 0092 update(); 0093 } 0094 } 0095 0096 void Killbots::NumericDisplayItem::setDigits(int digits) 0097 { 0098 if (digits != m_digits) { 0099 m_digits = digits; 0100 } 0101 } 0102 0103 void Killbots::NumericDisplayItem::setFont(const QFont &font) 0104 { 0105 m_font = font; 0106 m_boldFont = m_font; 0107 m_boldFont.setBold(true); 0108 0109 m_margin = int(QFontMetrics(m_boldFont).height() * 0.6); 0110 } 0111 0112 #include "moc_numericdisplayitem.cpp"