[Interest] Display nicely truncated text in a QLabel

Adam Light aclight at gmail.com
Mon Jul 22 23:13:22 CEST 2013


On Fri, Jul 12, 2013 at 2:06 AM, <Lucas.Betschart at crypto.ch> wrote:

> Hi
>
> I would derive from QLabel, get the length of it (in pixel) with
> frameWidth() use QFontMetrics QWidget::fontMetrics () with int
> QFontMetrics::width ( const QString & text, int len = -1 ) to get the
> length of the text in pixels, check if it fits, and if no cut some chars
> and replace it with … until it fits. You would have to check every time
> again when the user changes the windows size..
>
> Maybe someone else knows a nicer way.
>

There are potential complications with this approach depending on what
textInteractionFlags are set on the label. For example, in my application
we sometimes display paths to a file on disk, and we use
the Qt::TextSelectableByMouse flag so that the user can select that text
and copy it into another application, if they wish. Though I haven't tried
this, I suspect that if you used Lucas's approach of eliding the text then
you would only be able to select the elided text, not the original text. I
think you'd have similar problems if the label's text contained a link.

In my application, we work around this by using a QLineEdit set to be read
only with no frame and a transparent background. The user can then use the
mouse or keyboard cursors to move the cursor position in the line edit so
that they can see the beginning or end of the text that would otherwise be
hidden.

This work around isn't great, but it at least makes it possible for the
user to see the full value of the string in cases where it wouldn't
otherwise be possible.

Adam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130722/2cad309d/attachment.html>


More information about the Interest mailing list