python - 标签文本自动拉伸到它的父 pyqt5
问题描述
我正在尝试将标签中的文本拉伸到它的大小。
例如,如果我增加标签的高度,那么内部文本的大小应该只垂直增加。
如果我增加标签的宽度,那么内部文本的大小应该增加并且只能水平拉伸。
我怎样才能做到这一点?
解决方案
您可以使用 aQPainterPath
和 aQTransform
来变形您的文本:
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)
推荐阅读
- node.js - EJS 参考错误 - 未定义变量
- python - 我正在尝试从 Mersenner 素数列表中过滤掉,但它正在获取空值
- ruby-on-rails - 在 Rails 视图中从 React 组件重定向用户
- sql - sql计算每个组的运行总数和百分比
- python - 参数验证失败:\n参数 Filters[0].Values[0] 的类型无效,值:{},类型:
, 有效类型: - javascript - 如何使用纯 js 和 html 隐藏按钮 10 分钟
- docker - 如何将 dockerfile 转换为 Maven jib 插件的 XML,特别是“RUN”和“HEALTHCHECK”部分?
- c++ - C ++正确设计以迭代派生实例的成员
- windows-10 - anaconda 将软件包安装到错误的位置 windows 10
- neo4j - 在多个:“[:RATED]”任意:电影的用户之间创建“[FOLLOW]”关系