File indexing completed on 2024-05-19 04:07:47
0001 /* 0002 SPDX-FileCopyrightText: 2010 Stefan Majewsky <majewsky@gmx.net> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #include "elidinglabel.h" 0008 0009 #include <QFontMetrics> 0010 0011 Palapeli::ElidingLabel::ElidingLabel(QWidget* parent) 0012 : QLabel(parent) 0013 { 0014 setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); 0015 } 0016 0017 QString Palapeli::ElidingLabel::fullText() const 0018 { 0019 return m_fullText; 0020 } 0021 0022 QSize Palapeli::ElidingLabel::minimumSizeHint() const 0023 { 0024 Palapeli::ElidingLabel* mutableThis = const_cast<Palapeli::ElidingLabel*>(this); 0025 //calculate size hint from full text 0026 const QString elidedText = text(); 0027 mutableThis->setText(m_fullText); 0028 const QSize result = QLabel::minimumSizeHint(); 0029 mutableThis->setText(elidedText); 0030 //eliding is enabled by decreasing the minimum size hint 0031 return QSize(result.width() / 3, result.height()); 0032 } 0033 0034 QSize Palapeli::ElidingLabel::sizeHint() const 0035 { 0036 Palapeli::ElidingLabel* mutableThis = const_cast<Palapeli::ElidingLabel*>(this); 0037 //calculate size hint from full text 0038 const QString elidedText = text(); 0039 mutableThis->setText(m_fullText); 0040 const QSize result = QLabel::sizeHint(); 0041 mutableThis->setText(elidedText); 0042 //eliding is enabled by decreasing the size hint 0043 return QSize(result.width() / 3, result.height()); 0044 } 0045 0046 void Palapeli::ElidingLabel::setFullText(const QString& text) 0047 { 0048 m_fullText = text; 0049 resizeEvent(nullptr); //change text in label 0050 } 0051 0052 void Palapeli::ElidingLabel::resizeEvent(QResizeEvent* event) 0053 { 0054 if (event) 0055 QLabel::resizeEvent(event); 0056 //display elided text 0057 const QFontMetrics fm = fontMetrics(); 0058 const QString text = fm.elidedText(m_fullText, Qt::ElideRight, width()); 0059 setText(text); 0060 //enable tooltip with fullText if necessary 0061 setToolTip((text == m_fullText) ? QString() : m_fullText); 0062 }