問題描述
我正在嘗試使用沒有空格但用逗號分隔的文本制作多行 QLabel
.例如:'貓、狗、兔子、火車、汽車、飛機、奶酪、肉、門、窗'
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'
我發現使用 setWordWrap
可以實現多行,但它會根據空格中斷.
I have found that multiline is possible with setWordWrap
but it breaks based on spaces.
如何根據逗號換行?
這是一個代碼示例:
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_()
推薦答案
一種方法是根據 QLabel
大小編輯文本.
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()
然后我們用一個方法連接信號,設置 wordwrap 為 False 并添加自定義調整大小事件,每次標簽獲得新大小時觸發:
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
處理大小變化并觸發 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)
最后我們有一個 add_spaces
方法,它計算最大行長度并以逗號分隔.
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_()
這篇關于QLabel &自動換行:如何以逗號為基礎換行(與空格)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!