summaryrefslogtreecommitdiffstats
path: root/weather/src/painttextitem.cpp
blob: 586899de0003b50373794eece0045aacd54e0f57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: qt-info@nokia.com
**
** This software, including documentation, is protected by copyright
** controlled by Nokia Corporation.  You may use this software in
** accordance with the terms and conditions contained in the Qt Phone
** Demo License Agreement.
**
****************************************************************************/
#include "painttextitem.h"
#include <QPainter>
#include <QDebug>

TextPainter::TextPainter(int fontSize, QColor color, const QString &text)
    : m_pen(color)
    , m_brush(color)
    , m_text(text)
    , m_quoted(false)
    , m_maxWidth(-1)
{
    m_font.setFamily("Nokia Sans");
    m_font.setPixelSize(fontSize);
    m_font.setStyleStrategy(QFont::PreferAntialias);
    m_pen.setJoinStyle(Qt::RoundJoin);
}

int TextPainter::width() const
{
    QFontMetrics m(m_font);
    int result = 0;
    if (m_quoted)
        result += 2 * m.width('"');
    QString text = m_maxWidth > 0 ? m.elidedText(m_text, Qt::ElideRight, m_maxWidth - result)
                                  : m_text;
    return result + m.width(text);
}

void TextPainter::paint(QPainter *painter)
{
    QFontMetrics m(m_font);
    QString text;
    if (m_quoted) {
        int quote = 2 * m.width('"');
        text = m_maxWidth > 0 ? m.elidedText(m_text, Qt::ElideRight, m_maxWidth - quote) : m_text;
        text = '"' + text + '"';
    } else
        text = m_maxWidth > 0 ? m.elidedText(m_text, Qt::ElideRight, m_maxWidth) : m_text;
    painter->setFont(m_font);
    painter->setPen(m_pen);
    painter->setBrush(m_brush);

    painter->drawText(QPointF(m_pos.x(), m_pos.y() + m.ascent()), text);
}

void TextPainter::locateAtCenter(TextPainter *item, qreal left, qreal top, qreal width)
{
    item->setPos(left + (width - item->width()) / 2, top);
}

void TextPainter::locateAtCenter(QList<TextPainter*> items, qreal left, qreal top, qreal width)
{
    static const int margin = 5;

    if (items.isEmpty())
        return;

    int itemsWidth = (items.count() - 1) * margin;
    for (int i = 0; i < items.count(); ++i)
        itemsWidth += items[i]->width();

    left += (width - itemsWidth) / 2;
    for (int i = 0; i < items.count(); ++i) {
        items[i]->setPos(left, top);
        left += items[i]->width() + margin;
    }
}