【问题标题】:Label Text automatically stretch to it's parent pyqt5标签文本自动拉伸到它的父 pyqt5
【发布时间】:2020-10-12 03:37:08
【问题描述】:

我正在尝试将标签中的文本拉伸到它的大小。

例如,如果我增加标签的高度,那么内部文本的大小应该只在垂直方向上增加。

如果我增加标签的宽度,那么内部文本的大小应该增加并且只能水平拉伸。

我该怎么做?

【问题讨论】:

    标签: python text pyqt5 adjustment qsizepolicy


    【解决方案1】:

    您可以使用QPainterPathQTransform变形您的文本:

    QPainterPath 中使用任意字体大小绘制您的文本。根据小部件的大小和路径,您将获得比例因子。变换路径,然后绘制它:

    class Widget(QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
            self.text = "foobar"
    
        def paintEvent(self, event):
            super().paintEvent(event)
    
            painter = QPainter(self)
    
            textPath = QPainterPath()
            textPath.addText(QPointF(0, 0), painter.font(), self.text)
    
            size = textPath.boundingRect()
    
            scaleX = self.width() / size.width()
            scaleY = self.height() / size.height()
    
            transformation = QTransform()
            transformation.scale(scaleX, scaleY)
    
            textPath = transformation.map(textPath) # the text will be resized
            textPath.translate(0, textPath.boundingRect().height()) # path needs to be "recentered" after transformation
    
            painter.drawPath(textPath)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-16
      • 2022-01-18
      • 2023-03-17
      • 2013-12-13
      • 2016-10-17
      • 1970-01-01
      • 2015-07-11
      • 2012-01-07
      相关资源
      最近更新 更多