Search code examples
c++stringqtwidgetlabel

QLabel "break" word if too long


are there ways to allow QLabel breaks words if those words are too long? I've seen

q_label->setWordWrap(true)

but it works with spaces, but if a single word is too long, then it will overflow...
I would like something like word-break: break-all for web development

I've also seen QTextDocument but it does not allow to have a fixed width and a not-fixed height


Solution

  • Just put Zero-width space between each char

    from PySide2 import QtWidgets
    
    app = QtWidgets.QApplication()
    label = QtWidgets.QLabel()
    text = "TheBrownFoxJumpedOverTheLazyDog"
    label.setWordWrap(True)
    label.setText("\u200b".join(text))  # The magic is here.
    label.show()
    app.exec_()
    

    Or you can write your own QLabel

    from PySide2 import QtWidgets
    
    
    class HumanLabel(QtWidgets.QLabel):
        def __init__(self, text: str = "", parent: QtWidgets.QWidget = None):
            super().__init__("\u200b".join(text), parent)
            self.setWordWrap(True)
    
        def setText(self, arg__1: str) -> None:
            super().setText("\u200b".join(arg__1))
    
        def text(self) -> str:
            return super().text().replace("\u200b", "")
    
    
    app = QtWidgets.QApplication()
    text = "TheBrownFoxJumpedOverTheLazyDog"
    label = HumanLabel(text)
    assert label.text() == text
    label.show()
    app.exec_()
    

    Wikipedia: Zero-width space