subsurface/qt-ui/profile/divetextitem.cpp
Dirk Hohndel 487ddce353 Profile: make sure text is scaled correctly when drawn
We had all this wonderful code to scale the text correctly, except we went
out of our way to make sure the code wouldn't be called unless something
changed on this specific text item. But that's bogus because the scaling
depends on external factors like the fontPrintScale.

So instead of calling updateText() when attributes of this DiveTextItem
change simply call it right before the DiveTextItem gets painted.

Signed-off-by: Dirk Hohndel <dirk@hohndel.org>
2015-07-29 10:59:28 -07:00

90 lines
2.2 KiB
C++

#include "divetextitem.h"
#include "mainwindow.h"
#include "profilewidget2.h"
DiveTextItem::DiveTextItem(QGraphicsItem *parent) : QGraphicsItemGroup(parent),
internalAlignFlags(Qt::AlignHCenter | Qt::AlignVCenter),
textBackgroundItem(new QGraphicsPathItem(this)),
textItem(new QGraphicsPathItem(this)),
scale(1.0)
{
setFlag(ItemIgnoresTransformations);
textBackgroundItem->setBrush(QBrush(getColor(TEXT_BACKGROUND)));
textBackgroundItem->setPen(Qt::NoPen);
textItem->setPen(Qt::NoPen);
}
void DiveTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
updateText();
QGraphicsItemGroup::paint(painter, option, widget);
}
void DiveTextItem::setAlignment(int alignFlags)
{
if (alignFlags != internalAlignFlags) {
internalAlignFlags = alignFlags;
}
}
void DiveTextItem::setBrush(const QBrush &b)
{
textItem->setBrush(b);
}
void DiveTextItem::setScale(double newscale)
{
if (scale != newscale) {
scale = newscale;
}
}
void DiveTextItem::setText(const QString &t)
{
if (internalText != t) {
internalText = t;
}
}
const QString &DiveTextItem::text()
{
return internalText;
}
void DiveTextItem::updateText()
{
double size;
if (internalText.isEmpty()) {
return;
}
QFont fnt(qApp->font());
if ((size = fnt.pixelSize()) > 0) {
// set in pixels - so the scale factor may not make a difference if it's too close to 1
size *= scale * MainWindow::instance()->graphics()->getFontPrintScale();
fnt.setPixelSize(size);
} else {
size = fnt.pointSizeF();
size *= scale * MainWindow::instance()->graphics()->getFontPrintScale();
fnt.setPointSizeF(size);
}
QFontMetrics fm(fnt);
QPainterPath textPath;
qreal xPos = 0, yPos = 0;
QRectF rect = fm.boundingRect(internalText);
yPos = (internalAlignFlags & Qt::AlignTop) ? 0 :
(internalAlignFlags & Qt::AlignBottom) ? +rect.height() :
/*(internalAlignFlags & Qt::AlignVCenter ? */ +rect.height() / 4;
xPos = (internalAlignFlags & Qt::AlignLeft) ? -rect.width() :
(internalAlignFlags & Qt::AlignHCenter) ? -rect.width() / 2 :
/* (internalAlignFlags & Qt::AlignRight) */ 0;
textPath.addText(xPos, yPos, fnt, internalText);
QPainterPathStroker stroker;
stroker.setWidth(3);
textBackgroundItem->setPath(stroker.createStroke(textPath));
textItem->setPath(textPath);
}