def paintEvent(self, event):
        if self.elideMode == 0:  # if not set then behave as a normal label
            QLabel.paintEvent(self, event)
        else:
            QFrame.paintEvent(self, event)
            painter = QPainter(self)
            painter.setFont(self.font())

            # gets the spacing between lines
            lineSpacing = self.fontMetrics().lineSpacing()
            y = 0

            textLayout = QTextLayout(self.text(), self.font())
            textLayout.beginLayout()

            # loops  til the end of line
            while True:
                # create a line
                line = textLayout.createLine()

                if line.isValid() != True:
                    break
                self.lines += 1
                # set limit of line width
                line.setLineWidth(self.width())
                # calculate position of next line
                nextLineY = y + lineSpacing

                if self.height() >= nextLineY + lineSpacing:
                    line.draw(painter, QPoint(0, y))
                    y = nextLineY
                else:  # regenerate each line so that they do not overflow the width of widget
                    lastLine = self.text()[line.textStart():len(self.text())]
                    elidedLastLine = self.fontMetrics().elidedText(
                        lastLine, Qt.ElideRight, self.width())
                    painter.drawText(
                        QPoint(0, y + self.fontMetrics().ascent()),
                        elidedLastLine)
                    line = textLayout.createLine()
                    break
            textLayout.endLayout()
Example #2
0
	def text_layout(self, text, width, font, font_metrics):
		"Lays out wrapped text"
		text_option = QTextOption(Qt.AlignCenter)
		text_option.setUseDesignMetrics(True)
		text_option.setWrapMode(QTextOption.WordWrap)
		layout = QTextLayout(text, font)
		layout.setTextOption(text_option)
		leading = font_metrics.leading()
		height = 0
		layout.setCacheEnabled(True)
		layout.beginLayout()
		while True:
			line = layout.createLine()
			if not line.isValid():
				break
			line.setLineWidth(width)
			height += leading
			line.setPosition(QPointF(0, height))
			height += line.height()
		layout.endLayout()
		return layout