def __textLayout(self): fm = QFontMetrics(self.font()) text = six.text_type(self.defaultAction().iconText()) words = deque(text.split()) lines = [] curr_line = "" curr_line_word_count = 0 option = QStyleOptionToolButton() option.initFrom(self) margin = self.style().pixelMetric(QStyle.PM_ButtonMargin, option, self) width = self.width() - 2 * margin while words: w = words.popleft() if curr_line_word_count: line_extended = " ".join([curr_line, w]) else: line_extended = w line_w = fm.boundingRect(line_extended).width() if line_w >= width: if curr_line_word_count == 0 or len(lines) == 1: # A single word that is too long must be elided. # Also if the text overflows 2 lines # Warning: hardcoded max lines curr_line = fm.elidedText(line_extended, Qt.ElideRight, width) curr_line = six.text_type(curr_line) else: # Put the word back words.appendleft(w) lines.append(curr_line) curr_line = "" curr_line_word_count = 0 if len(lines) == 2: break else: curr_line = line_extended curr_line_word_count += 1 if curr_line: lines.append(curr_line) text = "\n".join(lines) self.__text = text