How to implement text ellipsis effect in QLabel?
-
I am using PySide6's QLabel, but I've found that when the text exceeds the label's width, it does not automatically display an ellipsis. Is there a way to achieve this? while also ensuring that QSS styles are still supported?
@yokuminto
So far as I can see, unfortunately you have to do this yourself. There is an incredibly large/detailed example at https://doc.qt.io/qt-5/qtwidgets-widgets-elidedlabel-example.html or something a lot shorter at https://stackoverflow.com/questions/7381100/text-overflow-for-a-qlabel-s-text-rendering. I think that will interoperate with QSS OK. -
@yokuminto
So far as I can see, unfortunately you have to do this yourself. There is an incredibly large/detailed example at https://doc.qt.io/qt-5/qtwidgets-widgets-elidedlabel-example.html or something a lot shorter at https://stackoverflow.com/questions/7381100/text-overflow-for-a-qlabel-s-text-rendering. I think that will interoperate with QSS OK.@JonB
Thank you very much!
Following the example you provided, I successfully rewrote the component in Python, and the ellipsis functionality works perfectly. Moreover, the component fully supports QSS styling as well—it looks fantastic!Thanks again for your help!
from PySide6.QtWidgets import QLabel from PySide6.QtCore import Qt from PySide6.QtGui import QFontMetrics class EllipsisLabel(QLabel): def __init__(self, text="", parent=None): super().__init__(parent) self._text = text self.setText(text) def setText(self, text): self._text = text self.updateText() def resizeEvent(self, event): super().resizeEvent(event) self.updateText() def updateText(self): metrics = QFontMetrics(self.font()) elided = metrics.elidedText(self._text, Qt.ElideRight, self.width()) super().setText(elided)
-