这包含在resizeEvent方法的重新实现中,QLabel的字体大小根据其contentRect的大小进行更新。注意,Qlabel的sizePolicy必须设置为Ignored,这样才能正常工作。在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() <&#61; cr.height() and br.width() <&#61; cr.width():
fs &#43;&#61; 1
else:
f.setPixelSize(max(fs - 1, 1)) # backtrack
break
# - update font size -
self.setFont(f)
class myApplication(QtGui.QWidget):
def __init__(self, parent&#61;None):
super(myApplication, self).__init__(parent)
# Prepare a Layout
grid &#61; QtGui.QGridLayout()
for i in range(3):
grid.addWidget(myQLabel(&#39;some text&#39;), i, 0)
grid.setRowStretch(i, i&#43;1)
grid.setRowMinimumHeight(i, 25)
self.setLayout(grid)
self.resize(500, 300)
if __name__ &#61;&#61; &#39;__main__&#39;:
app &#61; QtGui.QApplication(sys.argv)
instance &#61; myApplication()
instance.show()
sys.exit(app.exec_())
结果是&#xff1a;
更新-resizeEvent优化&#xff1a;
下面是resizeEvent方法的优化版本&#xff0c;它应该可以产生更好的性能。它大大减少了寻找字体大小的最佳值所需的迭代次数。不过&#xff0c;我还没有做过广泛的测试。在
^{pr2}$