6
votes

I am wondering how to best truncate text in a QLabel based on it's maximum width/height. The incoming text could be any length, but in order to keep a tidy layout I'd like to truncate long strings to fill a maximum amount of space (widget's maximum width/height).

E.g.:

 'A very long string where there should only be a short one, but I can't control input to the widget as it's a user given value'

would become:

'A very long string where there should only be a short one, but ...'

based on the required space the current font needs.

How can I achieve this best?

Here is a simple example of what I'm after, though this is based on word count, not available space:

import sys
from PySide.QtGui import *
from PySide.QtCore import *


def truncateText(text):
    maxWords = 10
    words = text.split(' ')
    return ' '.join(words[:maxWords]) + ' ...'

app = QApplication(sys.argv)

mainWindow = QWidget()
layout = QHBoxLayout()
mainWindow.setLayout(layout)

text = 'this is a very long string, '*10
label = QLabel(truncateText(text))
label.setWordWrap(True)
label.setFixedWidth(200)
layout.addWidget(label)

mainWindow.show()
sys.exit(app.exec_())
3

3 Answers

11
votes

Even easier - use the QFontMetrics.elidedText method and overload the paintEvent, here's an example:

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication,\
                        QLabel,\
                        QFontMetrics,\
                        QPainter

class MyLabel(QLabel):
    def paintEvent( self, event ):
        painter = QPainter(self)

        metrics = QFontMetrics(self.font())
        elided  = metrics.elidedText(self.text(), Qt.ElideRight, self.width())

        painter.drawText(self.rect(), self.alignment(), elided)

if ( __name__ == '__main__' ):
    app = None
    if ( not QApplication.instance() ):
        app = QApplication([])

    label = MyLabel()
    label.setText('This is a really, long and poorly formatted runon sentence used to illustrate a point')
    label.setWindowFlags(Qt.Dialog)
    label.show()

    if ( app ):
        app.exec_()
1
votes

I found that @Eric Hulser's answer, while great, didn't work when the label was put into another widget.

I came up with this by hacking together Eric's response and the Qt Elided Label Example. As written here, it allows for different elide modes to be passed in and preserves the text vertically (it's elided horizontally, of course!).

The layout phase, implemented according to the docs, isn't clear to me so I can't speak to that very well. Basically, it checks that the label text doesn't extend beyond the width of the label; if it does, it elides the text.

It's also not clear what's meant by a "valid" line. Removing those checks causes the app to crash. My guess is the line is valid when it doesn't extend beyond the widget.

If you want to use PySide,

  • PyQt5 -> PySide2
  • pyqtSignal -> Signal

Anyway, enjoy!

import sys
from PyQt5 import QtCore, QtWidgets, QtGui


class EliderLabel(QtWidgets.QLabel):

    elision_changed = QtCore.pyqtSignal(bool)

    def __init__(self, text='', mode=QtCore.Qt.ElideRight, **kwargs):
        super().__init__(**kwargs)

        self._mode = mode
        self.elided = False

        self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.setText(text)

    def setText(self, text):
        self._contents = text
        # Changing the content require a repaint of the widget (or so
        # says the overview)
        self.update()

    def text(self):
        return self._contents

    def minimumSizeHint(self):
        metrics = QtGui.QFontMetrics(self.font())
        return QtCore.QSize(0, metrics.height())

    def paintEvent(self, event):

        super().paintEvent(event)

        did_elide = False

        painter = QtGui.QPainter(self)
        font_metrics = painter.fontMetrics()
        # fontMetrics.width() is deprecated; use horizontalAdvance
        text_width = font_metrics.horizontalAdvance(self.text())

        # Layout phase, per the docs
        text_layout = QtGui.QTextLayout(self._contents, painter.font())
        text_layout.beginLayout()

        while True:

            line = text_layout.createLine()

            if not line.isValid():
                break

            line.setLineWidth(self.width())

            if text_width >= self.width():
                elided_line = font_metrics.elidedText(self._contents, self._mode, self.width())
                painter.drawText(QtCore.QPoint(0, font_metrics.ascent()), elided_line)
                did_elide = line.isValid()
                break
            else:
                line.draw(painter, QtCore.QPoint(0, 0))

        text_layout.endLayout()

        self.elision_changed.emit(did_elide)

        if did_elide != self.elided:
            self.elided = did_elide
            self.elision_changed.emit(did_elide)


class MyDialog(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()

        text = 'This is a really, long and poorly formatted runon sentence used to illustrate a point'
        label = EliderLabel(text, parent=self)

        label.elision_changed.connect(self.on_elide)

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(label)

        self.setLayout(layout)

    def on_elide(self, val):
        print('Elided: ', val, flush=True)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    dia = MyDialog()
    dia.show()

    sys.exit(app.exec_())

0
votes

You can achieves this through determining the width with QFontMetrics, see this answer.

You would probably want to use or create some algorithm which finds the place to cut quickly, unless doing it in a simple for loop would be sufficient.