Home > Software engineering >  QLabel setMinimumHeight After Custom WordWrap Qt.TextWrapAnywhere PyQt5 ( Full responsive With/Witho
QLabel setMinimumHeight After Custom WordWrap Qt.TextWrapAnywhere PyQt5 ( Full responsive With/Witho

Time:01-18

I want Qt.TextWrapAnywhere for my QLabel in a Layout.

I followed This instruction.My code is also same to give a minimal code

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QStyleOption, QVBoxLayout, QWidget, QStyle

class SuperQLabel(QLabel):
    def __init__(self, *args, **kwargs):
        super(SuperQLabel, self).__init__(*args, **kwargs)

        self.textalignment = Qt.AlignLeft | Qt.TextWrapAnywhere
        self.isTextLabel = True
        self.align = None

    def paintEvent(self, event):

        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)

        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

        self.style().drawItemText(painter, self.rect(),
                                  self.textalignment, self.palette(), True, self.text())


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.resize(100, 200)

        self.label = QLabel()
        self.label.setWordWrap(True)
        self.label.setText("11111111111111111111\n2222222211111111")

        self.slabel = SuperQLabel()
        self.slabel.setMinimumWidth(10)
        self.slabel.setText("111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")

        self.centralwidget = QWidget()
        self.setCentralWidget(self.centralwidget)

        self.mainlayout = QVBoxLayout()
        self.mainlayout.addWidget(self.label)
        self.mainlayout.addWidget(self.slabel)

        self.centralwidget.setLayout(self.mainlayout)


if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

I changed little bit that code self.slabel.setMinimumWidth(10) otherwise resizing Label according to width wont work.

It is perfectly wrapping the text according to width.But the Problem is when height is considered self.label = QLabel() Normal QLabel auto adjust height according to content with layout.

For example if i add one \n with text that means Qlabel must show 2 lines.

But with this new Custom Label e.g.self.slabel = SuperQLabel() wrapping is good as long as there is space for height in layout. I think i have to use setminimumHeight() but dont know how to get proper height after custom wrapping.

CodePudding user response:

After Some Research,I successfully fixed it. There is a trick

This is Full Responsive With/Without Emoji

  •  Tags:  
  • Related