One way of doing it would be to edit the text according to QLabel
size.
The following triggers on every line size event, making this a costly solution.
First we add a signal :
class MainWindow(QMainWindow):
resized = QtCore.pyqtSignal()
Then we connect signal with a method ,set wordwrap to False and add custom resize event that triggers every time label gets a new size:
self.line.setWordWrap(False)
self.line.resizeEvent = self.on_resize_event
self.resized.connect(self.add_spaces)
on_resize_event
which handles size changes and triggers add_spaces
:
def on_resize_event(self, event):
if not self._flag:
self._flag = True
self.resized.emit()
QtCore.QTimer.singleShot(100, lambda: setattr(self, "_flag", False))
print(f"Resized line: {self.line.size()}")
return super(MainWindow, self).resizeEvent(event)
Lastly we have a add_spaces
method which calculates maximum line length and splits on comma.
def add_spaces(self):
size = self.line.size()
text = self.mystring
result_string = ""
temp_label = QLabel()
temp_text = ""
#Split the chunks by delimiter
chunks = text.split(",")
for i,chunk in enumerate(chunks):
temp_text += chunk + ",";
if len(chunks) > i+1:
temp_label.setText(temp_text + chunks[i+1] + ",")
width = temp_label.fontMetrics().boundingRect(temp_label.text()).width()
if width >= size.width():
result_string += temp_text + "\n"
temp_text = ""
else:
result_string += temp_text
self.line.setText(result_string)
Full code:
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow, QLabel, QApplication
class MainWindow(QMainWindow):
resized = QtCore.pyqtSignal()
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self._flag = False
self.line = QLabel()
self.line.setStyleSheet("background-color: grey;color:white;")
self.line.setMaximumWidth(300)
self.line.setMinimumWidth(20)
self.mystring = 'Cat,Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window,very,long,list of words,list of words,word,word,word,list of word,word,list of word,list of word'
self.line.setText(self.mystring)
self.setCentralWidget(self.line)
self.line.setWordWrap(False)
self.line.resizeEvent = self.on_resize_event
self.resized.connect(self.add_spaces)
self.show()
self.add_spaces()
def on_resize_event(self, event):
if not self._flag:
self._flag = True
self.resized.emit()
QtCore.QTimer.singleShot(100, lambda: setattr(self, "_flag", False))
print(f"Resized line: {self.line.size()}")
return super(MainWindow, self).resizeEvent(event)
def add_spaces(self):
size = self.line.size()
text = self.mystring
result_string = ""
temp_label = QLabel()
temp_text = ""
#Split the chunks by delimiter
chunks = text.split(",")
for i,chunk in enumerate(chunks):
temp_text += chunk + ",";
if len(chunks) > i+1:
temp_label.setText(temp_text + chunks[i+1] + ",")
width = temp_label.fontMetrics().boundingRect(temp_label.text()).width()
if width >= size.width():
result_string += temp_text + "\n"
temp_text = ""
else:
result_string += temp_text
self.line.setText(result_string)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
app.exec_()
\u200b
) after every comma, since word-wrapping breaks after any kind of whitespace. – Aryanize