1 /**************************************************************************** 2 ** 3 ** Copyright (C) 2016 Jochen Becher 4 ** Contact: https://www.qt.io/licensing/ 5 ** 6 ** This file is part of Qt Creator. 7 ** 8 ** Commercial License Usage 9 ** Licensees holding valid commercial Qt licenses may use this file in 10 ** accordance with the commercial license agreement provided with the 11 ** Software or, alternatively, in accordance with the terms contained in 12 ** a written agreement between you and The Qt Company. For licensing terms 13 ** and conditions see https://www.qt.io/terms-conditions. For further 14 ** information use the contact form at https://www.qt.io/contact-us. 15 ** 16 ** GNU General Public License Usage 17 ** Alternatively, this file may be used under the terms of the GNU 18 ** General Public License version 3 as published by the Free Software 19 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT 20 ** included in the packaging of this file. Please review the following 21 ** information to ensure the GNU General Public License requirements will 22 ** be met: https://www.gnu.org/licenses/gpl-3.0.html. 23 ** 24 ****************************************************************************/ 25 26 #include "contextlabelitem.h" 27 28 #include <QFontMetricsF> 29 30 namespace qmt { 31 ContextLabelItem(QGraphicsItem * parent)32ContextLabelItem::ContextLabelItem(QGraphicsItem *parent) 33 : QGraphicsSimpleTextItem(parent) 34 { 35 } 36 ~ContextLabelItem()37ContextLabelItem::~ContextLabelItem() 38 { 39 } 40 setMaxWidth(double maxWidth)41void ContextLabelItem::setMaxWidth(double maxWidth) 42 { 43 if (m_maxWidth != maxWidth) { 44 m_maxWidth = maxWidth; 45 update(); 46 } 47 } 48 resetMaxWidth()49void ContextLabelItem::resetMaxWidth() 50 { 51 if (m_maxWidth != 0.0) { 52 m_maxWidth = 0.0; 53 update(); 54 } 55 } 56 setContext(const QString & context)57void ContextLabelItem::setContext(const QString &context) 58 { 59 if (m_context != context) { 60 m_context = context; 61 update(); 62 } 63 } 64 height() const65double ContextLabelItem::height() const 66 { 67 return QFontMetricsF(font()).height(); 68 } 69 update()70void ContextLabelItem::update() 71 { 72 setText(QString("(from %1)").arg(m_context)); 73 if (m_maxWidth > 0.0) { 74 double contextWidth = boundingRect().width(); 75 if (contextWidth > m_maxWidth) { 76 setText(QString("(%1)").arg(m_context)); 77 contextWidth = boundingRect().width(); 78 } 79 if (contextWidth > m_maxWidth) { 80 QFontMetricsF metrics(font()); 81 setText(metrics.elidedText(QString("(%1)").arg(m_context), Qt::ElideMiddle, m_maxWidth)); 82 } 83 } 84 } 85 86 } // namespace qmt 87