1
更改標籤字體大小以匹配其通過信號/插槽中包含的佈局大小的具體方法是什麼?將標籤字體大小與PyQt中的佈局同步
更改標籤字體大小以匹配其通過信號/插槽中包含的佈局大小的具體方法是什麼?將標籤字體大小與PyQt中的佈局同步
下面是解決方案,對於QLabel
,從此處發佈的解決方案派生而來:https://forum.qt.io/topic/36088/automatically-scale-text-in-qlabels/5。
這包括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() <= 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_())
導致:
更新 - resizeEvent的優化:
下面是resizeEvent
方法應該得到更好的性能的優化版本。它大大減少了查找字體大小的最佳值所需的迭代次數。儘管如此,我還沒有廣泛測試過。
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)
我該如何給標籤初始尺寸?忽略大小策略後可能嗎? – Amen
@Amen好吧,標籤的初始大小主要取決於應用程序的佈局。但是我可以看到,在標籤上設置最小尺寸可能很有用,因此不會因UI的其他元素的拉伸而摺疊。查看更新的示例。 –