我想知道如何根据它的最大宽度/高度最好地截断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'
Run Code Online (Sandbox Code Playgroud)
会成为:
'A very long string where there should only be a short one, but ...'
Run Code Online (Sandbox Code Playgroud)
基于当前字体所需的空间.
我怎样才能做到最好?
这是我所追求的一个简单示例,虽然这是基于字数,而不是可用空间:
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_())
Run Code Online (Sandbox Code Playgroud)
更简单 - 使用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_()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3298 次 |
| 最近记录: |