PySide / PyQt trims text in QLabel based on minimumSize

I am wondering what is the best way to crop text in QLabel based on maximum width / height. The incoming text can be of any length, but in order to maintain a neat layout, I would like to truncate long lines to fill the maximum amount of space (maximum width / height of the widget).

eg:.

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

will become:

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

based on the required space that the current font needs.

How can I achieve this better?

Here is a simple example of what I need, although this is based on word counting, inaccessible 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_())
+5
source share
2 answers

Even simpler - use the QFontMetrics.elidedText method and overload paintEvent, here is 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_()
+9
source

, QFontMetrics, . .

, , - , , for .

0

All Articles