如何获得QLabel的当前宽度?

问题描述 投票:0回答:1

在这里,标签被切掉,猫的imageLabel图片的值是x = 0,y =标签的高度。

The label is Cut

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)
python python-3.x layout pyqt5 qlabel
1个回答
0
投票

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

UPDATE

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

下面是解决这些问题的演示:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS96Z2g5US5wbmcifQ==” alt =“在此处输入图像描述”>

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, 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_()
© www.soinside.com 2019 - 2024. All rights reserved.