将标签字体大小与 PyQt 中的布局同步 [英] Syncing Label fontsize with layout in PyQt

查看:95
本文介绍了将标签字体大小与 PyQt 中的布局同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更改标签字体大小以匹配其通过信号/插槽中包含的布局大小的具体方法是什么?

解决方案

下面是一个用于 QLabel 的解决方案,派生自此处发布的解决方案:

更新 - resizeEvent 的优化:

以下是 resizeEvent 方法的优化版本,应该会产生更好的性能.它大大减少了找到字体大小的最佳值所需的迭代次数.不过我还没有对其进行广泛的测试.

def resizeEvent(self, event):super(myQLabel, self).resizeEvent(event)如果不是 self.text():返回#--- 获取当前参数 ----f = self.font()cr = self.contentsRect()#--- 迭代以找到适合 contentsRect 的字体大小 ---dw = event.size().width() - event.oldSize().width() # 宽度变化dh = event.size().height() - event.oldSize().height() # 高度变化fs = max(f.pixelSize(), 1)为真:f.setPixelSize(fs)br = QtGui.QFontMetrics(f).boundingRect(self.text())if dw >= 0 and dh >= 0: # 标签正在扩展如果 br.height() <= cr.height() 和 br.width() <= cr.width():fs += 1别的:f.setPixelSize(max(fs - 1, 1)) # 回溯休息else: # 标签正在缩小如果 br.height() >cr.height() 或 br.width() >cr.width():fs -= 1别的:休息如果 fs <1:打破#--- 更新字体大小---self.setFont(f)

What is the concrete way to change the font size of a label to match the layout size its contained in through signal/slots?

解决方案

Below is a solution, for a QLabel, derived from the solution posted here: https://forum.qt.io/topic/36088/automatically-scale-text-in-qlabels/5.

This consists in a reimplementation of the resizeEvent method where the font size of the QLabel is updated according to the size of its contentRect. Note that the sizePolicy of the Qlabel has to be set to Ignored for this to work properly.

import sys
from PyQt4 import QtGui     

class myQLabel(QtGui.QLabel):
    def __init__(self, *args, **kargs):
        super(myQLabel, self).__init__(*args, **kargs)

        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored,
                                             QtGui.QSizePolicy.Ignored))  

        self.setMinSize(14)

    def setMinSize(self, minfs):        

        f = self.font()
        f.setPixelSize(minfs)
        br = QtGui.QFontMetrics(f).boundingRect(self.text())

        self.setMinimumSize(br.width(), br.height())

    def resizeEvent(self, event):
        super(myQLabel, self).resizeEvent(event)

        if not self.text():
            return

        #--- fetch current parameters ----

        f = self.font()
        cr = self.contentsRect()

        #--- find the font size that fits the contentsRect ---

        fs = 1                    
        while True:

            f.setPixelSize(fs)
            br =  QtGui.QFontMetrics(f).boundingRect(self.text())

            if br.height() <= cr.height() and br.width() <= cr.width():
                fs += 1
            else:
                f.setPixelSize(max(fs - 1, 1)) # backtrack
                break  

        #--- update font size ---

        self.setFont(f)     


class myApplication(QtGui.QWidget):
    def __init__(self, parent=None):
        super(myApplication, self).__init__(parent)

        #---- Prepare a Layout ----

        grid = QtGui.QGridLayout()  

        for i in range(3):
            grid.addWidget(myQLabel('some text'), i, 0)  
            grid.setRowStretch(i, i+1)
            grid.setRowMinimumHeight(i, 25)

        self.setLayout(grid)
        self.resize(500, 300)


if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    instance = myApplication()  
    instance.show()    

    sys.exit(app.exec_())

Which results in:

Update - Optimization of resizeEvent :

Below is an optimized version of the resizeEvent method that should yield better performances. It drastically reduces the number of iteration required to find the optimal value of the font size. I haven't tested it extensively though.

def resizeEvent(self, event):
    super(myQLabel, self).resizeEvent(event)        

    if not self.text():
        return

    #--- fetch current parameters ----

    f = self.font()
    cr = self.contentsRect()

    #--- iterate to find the font size that fits the contentsRect ---

    dw = event.size().width() - event.oldSize().width()   # width change
    dh = event.size().height() - event.oldSize().height() # height change

    fs = max(f.pixelSize(), 1)        
    while True:

        f.setPixelSize(fs)
        br =  QtGui.QFontMetrics(f).boundingRect(self.text())

        if dw >= 0 and dh >= 0: # label is expanding

            if br.height() <= cr.height() and br.width() <= cr.width():
                fs += 1
            else:
                f.setPixelSize(max(fs - 1, 1)) # backtrack
                break                    

        else: # label is shrinking

            if br.height() > cr.height() or br.width() > cr.width():
                fs -= 1
            else:
                break

        if fs < 1: break

    #--- update font size ---           

    self.setFont(f)   

这篇关于将标签字体大小与 PyQt 中的布局同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆