問題描述
我正在嘗試使用沒有空格但用逗號(hào)分隔的文本制作多行 QLabel
.例如:'貓、狗、兔子、火車、汽車、飛機(jī)、奶酪、肉、門、窗'
I am trying to make a multi line QLabel
with a text without space but delimited by comma.
ex : 'Cat,Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window'
我發(fā)現(xiàn)使用 setWordWrap
可以實(shí)現(xiàn)多行,但它會(huì)根據(jù)空格中斷.
I have found that multiline is possible with setWordWrap
but it breaks based on spaces.
如何根據(jù)逗號(hào)換行?
這是一個(gè)代碼示例:
from PySide2.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setGeometry(500,100,50,100)
line = QLabel()
line.setMaximumWidth(150)
line.setText('Cat,Dog,Rabbit,Train,Car,Plane,Cheese,Meat,Door,Window')
line.setWordWrap(True)
self.setCentralWidget(line)
self.show()
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
app.exec_()
推薦答案
一種方法是根據(jù) QLabel
大小編輯文本.
One way of doing it would be to edit the text according to QLabel
size.
以下觸發(fā)器會(huì)觸發(fā)每個(gè)行大小事件,因此這是一個(gè)成本高昂的解決方案.
The following triggers on every line size event, making this a costly solution.
首先我們添加一個(gè)信號(hào):
First we add a signal :
class MainWindow(QMainWindow):
resized = QtCore.pyqtSignal()
然后我們用一個(gè)方法連接信號(hào),設(shè)置 wordwrap 為 False 并添加自定義調(diào)整大小事件,每次標(biāo)簽獲得新大小時(shí)觸發(fā):
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
處理大小變化并觸發(fā) 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)
最后我們有一個(gè) add_spaces
方法,它計(jì)算最大行長(zhǎng)度并以逗號(hào)分隔.
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 + "
"
temp_text = ""
else:
result_string += temp_text
self.line.setText(result_string)
完整代碼:
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 + "
"
temp_text = ""
else:
result_string += temp_text
self.line.setText(result_string)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
app.exec_()
這篇關(guān)于QLabel &自動(dòng)換行:如何以逗號(hào)為基礎(chǔ)換行(與空格)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!