4d10065c54
Conflicts: examples/widgets/applicationicon/applicationicon.svg examples/widgets/applicationicon/main.cpp examples/widgets/elidedlabel/elidedlabel.cpp examples/widgets/elidedlabel/elidedlabel.h examples/widgets/elidedlabel/main.cpp examples/widgets/elidedlabel/testwidget.cpp examples/widgets/elidedlabel/testwidget.h (cherry picked from commit 1b555a91f05b68c697b6985d1b672dc0fba5fc5a) (cherry picked from commit c0e0bfdd451f42b10051e8064153b811080ffa0e)
72 lines
1.6 KiB
C++
72 lines
1.6 KiB
C++
#include "elidedlabel.h"
|
|
|
|
#include <QPainter>
|
|
#include <QTextLayout>
|
|
#include <QDebug>
|
|
|
|
//! [0]
|
|
ElidedLabel::ElidedLabel(const QString &text, QWidget *parent)
|
|
: QFrame(parent)
|
|
, elided(false)
|
|
, content(text)
|
|
{
|
|
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
|
|
}
|
|
//! [0]
|
|
|
|
//! [1]
|
|
void ElidedLabel::setText(const QString &newText)
|
|
{
|
|
content = newText;
|
|
update();
|
|
}
|
|
//! [1]
|
|
|
|
//! [2]
|
|
void ElidedLabel::paintEvent(QPaintEvent *event)
|
|
{
|
|
QFrame::paintEvent(event);
|
|
|
|
QPainter painter(this);
|
|
QFontMetrics fontMetrics = painter.fontMetrics();
|
|
|
|
bool didElide = false;
|
|
int lineSpacing = fontMetrics.lineSpacing();
|
|
int y = 0;
|
|
|
|
QTextLayout textLayout(content, painter.font());
|
|
textLayout.beginLayout();
|
|
forever {
|
|
QTextLine line = textLayout.createLine();
|
|
|
|
if (!line.isValid())
|
|
break;
|
|
|
|
line.setLineWidth(width());
|
|
int nextLineY = y + lineSpacing;
|
|
|
|
if (height() >= nextLineY + lineSpacing) {
|
|
line.draw(&painter, QPoint(0, y));
|
|
y = nextLineY;
|
|
//! [2]
|
|
//! [3]
|
|
} else {
|
|
QString lastLine = content.mid(line.textStart());
|
|
QString elidedLastLine = fontMetrics.elidedText(lastLine, Qt::ElideRight, width());
|
|
painter.drawText(QPoint(0, y + fontMetrics.ascent()), elidedLastLine);
|
|
line = textLayout.createLine();
|
|
didElide = line.isValid();
|
|
break;
|
|
}
|
|
}
|
|
textLayout.endLayout();
|
|
//! [3]
|
|
|
|
//! [4]
|
|
if (didElide != elided) {
|
|
elided = didElide;
|
|
emit elisionChanged(didElide);
|
|
}
|
|
}
|
|
//! [4]
|