gpt4 book ai didi

python - 如何在 PyQt5 QLabel (Fixed Size) 中增加/减少字体大小?

转载 作者:行者123 更新时间:2023-12-04 09:45:15 27 4
gpt4 key购买 nike

在我的代码中,使用一个具有固定尺寸/大小的 QLabel。一开始,我分配文本 “你好,Python”到 那个QLablel .现在我要更改 QLablel 的文本 到“嗨,欢迎使用 Python”。

如何减小QLabel字体大小,显示全文具有该特定区域/大小(没有任何切断/隐藏/隐藏)?

import sys
from PyQt5.QtWidgets import *


class Labelexample(QWidget):
def __init__(self):
super().__init__()
self.labl = QLabel("Hello,Python",self)
self.tbox = QLineEdit(self)
self.labl.setFixedSize(150,30)
self.tbox.setFixedSize(200,30)
self.labl.move(50,50)
self.tbox.move(140,50)
self.labl.setText("Hai, welcome to Python")
# self.labl.adjustsize()

app = QApplication(sys.argv)
mywin = Labelexample()
mywin.show()
sys.exit(app.exec_())

最佳答案

QFontMetrics 类提供字体度量信息。 https://doc.qt.io/qt-5/qfontmetrics.html#QFontMetrics

尝试一下:

import sys
from PyQt5.Qt import *


class Labelexample(QWidget):
def __init__(self):
super().__init__()

text = "Hello,Python"
self.labl = QLabel(text, self)
# self.labl.setFixedSize(150,30)
self.labl.setFixedWidth(150) # +++
self.labl.setMinimumHeight(30) # +++

self.labl.move(50,50)
self.labl.setStyleSheet("background-color: yellow;")

self.tbox = QLineEdit(self)
self.tbox.setFixedSize(200,30)
# self.tbox.move(140,50)
self.tbox.move(200,50)
self.tbox.returnPressed.connect(self.return_pressed) # +++

self.pointSize = 20 # 20
self.fontD = self.font()
self.fontD.setPointSize(self.pointSize)
self.metrics = QFontMetrics(self.fontD)
self.width = self.metrics.width(text)
self.height = self.metrics.height()
self.labl.setFixedWidth(self.width)
self.labl.setFont(self.fontD)

# text = "Hai, welcome to Python"
# self.labl.setText(text) # v v
self.labl.adjustSize() # - adjustsize + adjustSize

def return_pressed(self): # +++
if not self.tbox.text():
self.labl.setText('')
self.labl.setFont(self.fontD)
self.labl.adjustSize()
return
width = self.metrics.width(self.tbox.text())
height = self.metrics.height()

if not width:
width = 1

koef = self.width / width
pointSize = int(self.pointSize * koef)
font = self.font()
font.setPointSize(pointSize)
self.labl.setFont(font)
height = self.metrics.height()
self.labl.setText(self.tbox.text())
self.labl.adjustSize()


if __name__ == '__main__':
app = QApplication(sys.argv)
mywin = Labelexample()
mywin.resize(450, 415)
mywin.show()
sys.exit(app.exec_())

enter image description here

关于python - 如何在 PyQt5 QLabel (Fixed Size) 中增加/减少字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62155504/

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