基于最小大小的PySide/PyQt截断QLabel中的文本 [英] PySide/PyQt truncate text in QLabel based on minimumSize
本文介绍了基于最小大小的PySide/PyQt截断QLabel中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何根据QLabel的最大宽度/高度最好地截断文本。 传入的文本可以是任何长度,但是为了保持布局整洁,我想截断长字符串以填充最大空间(小部件的最大宽度/高度)。
例如:
'A very long string where there should only be a short one, but I can't control input to the widget as it's a user given value'
将变为:
'A very long string where there should only be a short one, but ...'
基于当前字体所需的空间。
如何才能最好地实现此目标?
下面是我想要的一个简单示例,尽管这是基于字数,而不是可用空间:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
def truncateText(text):
maxWords = 10
words = text.split(' ')
return ' '.join(words[:maxWords]) + ' ...'
app = QApplication(sys.argv)
mainWindow = QWidget()
layout = QHBoxLayout()
mainWindow.setLayout(layout)
text = 'this is a very long string, '*10
label = QLabel(truncateText(text))
label.setWordWrap(True)
label.setFixedWidth(200)
layout.addWidget(label)
mainWindow.show()
sys.exit(app.exec_())
推荐答案
更简单-使用QFontMetrics.elidedText方法并重载PaintEvent,下面是一个示例:
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication,
QLabel,
QFontMetrics,
QPainter
class MyLabel(QLabel):
def paintEvent( self, event ):
painter = QPainter(self)
metrics = QFontMetrics(self.font())
elided = metrics.elidedText(self.text(), Qt.ElideRight, self.width())
painter.drawText(self.rect(), self.alignment(), elided)
if ( __name__ == '__main__' ):
app = None
if ( not QApplication.instance() ):
app = QApplication([])
label = MyLabel()
label.setText('This is a really, long and poorly formatted runon sentence used to illustrate a point')
label.setWindowFlags(Qt.Dialog)
label.show()
if ( app ):
app.exec_()
这篇关于基于最小大小的PySide/PyQt截断QLabel中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文