Many people have asked for an widgets like labels or buttons that can elide their text as the size of the widget underruns the text length in a visually appealing way. Text ellipses already happens: most widgets (or, since Qt abstracts that, many styles) use '...'. However, that doesn't really look good and it was suggested that ellipsis could be better signified by fading out the last two letters. Dolphin has a hack to achive this with Qt 3, and it is incredibly complicated. So I sat down and looked what it takes to do it better with Qt 4. This is what the result looks like:
Note how the entire sentence is still readable now (at least for the majority of people), and it was really easy to do: I implemented a QLabel subclass that takes 6 lines of code in the paint event to do the actual fading using
QGradient:
void ElideLabel::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter p(this);
QFontMetrics fm(font());
if (fm.width(text()) > contentsRect().width()) {
QLinearGradient gradient(contentsRect().topLeft(), contentsRect().topRight());
gradient.setColorAt(0.8, palette().color(QPalette::WindowText));
gradient.setColorAt(1.0, palette().color(QPalette::Window));
QPen pen;
pen.setBrush(QBrush(gradient));
p.setPen(pen);
}
p.drawText(rect(), Qt::TextSingleLine, text());
}
Yeah, really, that's it. Nothing more to see here. Yes I know, The code doesn't pass on all text flags that the QLabel API accepts, but hey, it's a demo. One that made Peter want to replace the old algorithm in Dolphin with a
QGradient-based one. The real trick here was to realize that constructing a pen with a brush inherits the gradient. Thanks to Zack for the hint!