File indexing completed on 2024-05-19 05:42:16

0001 // ct_lvtqtc_ellipsistextitem.cpp                                     -*-C++-*-
0002 
0003 /*
0004 // Copyright 2023 Codethink Ltd <codethink@codethink.co.uk>
0005 // SPDX-License-Identifier: Apache-2.0
0006 //
0007 // Licensed under the Apache License, Version 2.0 (the "License");
0008 // you may not use this file except in compliance with the License.
0009 // You may obtain a copy of the License at
0010 //
0011 //     http://www.apache.org/licenses/LICENSE-2.0
0012 //
0013 // Unless required by applicable law or agreed to in writing, software
0014 // distributed under the License is distributed on an "AS IS" BASIS,
0015 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0016 // See the License for the specific language governing permissions and
0017 // limitations under the License.
0018 */
0019 
0020 #include <ct_lvtqtc_ellipsistextitem.h>
0021 
0022 #include <QFontMetrics>
0023 #include <QString>
0024 
0025 namespace {
0026 
0027 constexpr QString::size_type MAXIMUM_LABEL_LENGTH = 15;
0028 }
0029 
0030 namespace Codethink::lvtqtc {
0031 
0032 struct EllipsisTextItem::Private {
0033     EllipsisTextItem::Truncate truncate = EllipsisTextItem::Truncate::Yes;
0034     QString fullText;
0035 };
0036 
0037 EllipsisTextItem::EllipsisTextItem(const QString& text, QGraphicsItem *parent):
0038     QGraphicsSimpleTextItem(parent), d(std::make_unique<EllipsisTextItem::Private>())
0039 {
0040     d->fullText = text;
0041     setText(text);
0042 }
0043 
0044 EllipsisTextItem::~EllipsisTextItem() = default;
0045 
0046 void EllipsisTextItem::setText(const QString& text)
0047 {
0048     d->fullText = text;
0049     setupText();
0050 }
0051 
0052 void EllipsisTextItem::truncate(EllipsisTextItem::Truncate v)
0053 {
0054     d->truncate = v;
0055     setupText();
0056 }
0057 
0058 void EllipsisTextItem::setupText()
0059 {
0060     QString myText = d->fullText;
0061     if (d->truncate == EllipsisTextItem::Truncate::Yes && d->fullText.length() > MAXIMUM_LABEL_LENGTH) {
0062         myText.truncate(MAXIMUM_LABEL_LENGTH);
0063         myText += "...";
0064     }
0065     QGraphicsSimpleTextItem::setText(myText);
0066 }
0067 
0068 } // namespace Codethink::lvtqtc