2012-07-12 33 views
5

我想知道如何根據最大寬度/高度來最好地截斷QLabel中的文本。 傳入的文本可以是任意長度,但爲了保持整齊的佈局,我想截斷長字符串以填充最大量的空間(小部件的最大寬度/高度)。PySide/PyQt基於最小尺寸在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_()) 

回答

8

甚至更​​容易 - 使用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_() 
+0

哇,非常酷,謝謝! – 2012-08-01 22:33:22

+0

@EricHulser,這是一個非常好的答案。很有用。非常感謝! – Phil 2013-03-12 17:15:41

0

您可以通過確定與QFontMetrics寬度達到這一點,看到this answer

您可能想要使用或創建一些算法,以找到需要快速切割的位置,除非在簡單的for循環中執行就足夠了。

+0

甜蜜的,謝謝! – 2012-07-12 23:51:20