如何获得QLabel的当前高度?

在这里,标签被切开,猫的imageLabel图片具有x = 0和y =标签高度的值。

如何获得QLabel的当前高度?

layout = QVBoxLayout()

widget = QWidget()

label = QLabel("Lourim Ipsum ...",parent=widget) # LONG TEXT
label.setWordWard(True)

image = QPixmap("cat.png")
imageLabel = QLabel(parent=widget)
imageLabel.setPixmap(image)
imageLabel.setGeometry(0,label.height(),image.width(),image.height())

layout.addWidget(widget)
  

更新:

我通过在setWordWrap之后做一些数学运算来解决了这个问题

layout = QVBoxLayout()

widget = QWidget()

label = QLabel("Lourim Ipsum ...",parent=widget) # LONG TEXT
label.setWordWard(True)
labe.adjustSize() # THE MOST IMPORTANT LINE

image = QPixmap("cat.png")
imageLabel = QLabel(parent=widget)
imageLabel.setPixmap(image)
  

自布局的默认宽度开始,将其恒定宽度设置为761,并将高度设置为此高度

dec = image.width()/761
wid = round(image.width()/dec) # Which will be 761.0 rounded to 761
hei = round(image.height()/dec)
imageLabel.setGeometry(0,wid,hei)
imageLabel.adjustSize()

layout.addWidget(widget)
sacklise 回答:如何获得QLabel的当前高度?

必须在顶部标签上正确设置自动换行,并且两个标签都必须添加到布局中。还必须在容器窗口小部件上设置布局。不必设置标签的几何形状,因为布局会自动完成。

更新

有一个problem with layouts that contain labels with word-wrapping。看来高度计算有时可能是错误的,这意味着小部件可能会重叠。

下面是一个修复这些问题的演示:

enter image description here

import sys
from PyQt5 import QtCore,QtGui,QtWidgets

app = QtWidgets.QApplication(sys.argv)

TITLE = 'Cat for sale: Mint condition,still in original packaging'

class Widget(QtWidgets.QWidget):
    def __init__(self,parent=None):
        super().__init__(parent)
        layout = QtWidgets.QVBoxLayout(self)
        layout.setContentsMargins(10,10,10)
        self.label = QtWidgets.QLabel(TITLE)
        self.label.setWordWrap(True)
        image = QtGui.QPixmap('cat.png')
        self.imageLabel = QtWidgets.QLabel()
        self.imageLabel.setPixmap(image)
        self.imageLabel.setFixedSize(image.size() + QtCore.QSize(0,10))
        layout.addWidget(self.label)
        layout.addWidget(self.imageLabel)
        layout.addStretch()

    def resizeEvent(self,event):
        super().resizeEvent(event)
        height = self.label.height() + self.imageLabel.height()
        height += self.layout().spacing()
        margins = self.layout().contentsMargins()
        height += margins.top() + margins.bottom()
        if self.height() < height:
            self.setMinimumHeight(height)
        elif height < self.minimumHeight():
            self.setMinimumHeight(1)

widget= Widget()
widget.setStyleSheet('''
    background-color: purple;
    color: white;
    font-size: 26pt;
    ''')
widget.setWindowTitle('Test')
widget.setGeometry(100,100,500,500)
widget.show()

app.exec_()
本文链接:https://www.f2er.com/3051060.html

大家都在问