gpt4 book ai didi

qt - PySide/PyQt根据minimumSize截断QLabel中的文本

转载 作者:行者123 更新时间:2023-12-04 13:19:59 26 4
gpt4 key购买 nike

我想知道如何根据最大标签的最大宽度/高度截断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_()

关于qt - PySide/PyQt根据minimumSize截断QLabel中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11446478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com