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_())
source
share