0

My PyQt application includes a QHBoxLayout which contains two QLabels, one with static text and another with dynamic content. The minimal code is as follows:

from PyQt5.QtWidgets import QMainWindow, QHBoxLayout, QLabel, QApplication, QWidget, QSizePolicy
from PyQt5.QtCore import Qt

class Window(QMainWindow):

    def __init__(self):
        super().__init__()

        mainLabel = QLabel()
        mainLabel.setContentsMargins(10, 5, 10, 5)
        mainLabel.setText('Main Label')
        mainLabel.setAlignment(Qt.AlignLeft)
        mainLabel.setStyleSheet("font: 13pt; font-weight: bold; color: darkblue")
        mainLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)

        label = QLabel()
        label.setContentsMargins(10, 5, 10, 5)
        label.setText("<span style='color: blue'>Lorem ipsum dolor sit amet,</span> <span style='color: red'> consectetur adipiscing elit,</span>")
        label.setAlignment(Qt.AlignRight)
        label.setStyleSheet("font: 10pt")

        hbox = QHBoxLayout()
        hbox.addWidget(mainLabel)
        hbox.addWidget(label)

        mainWidget = QWidget()
        mainWidget.setFixedHeight(50)
        mainWidget.setLayout(hbox)
        mainWidget.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)

        self.setCentralWidget(mainWidget)
        self.setFixedHeight(50)

        self.show()
        self.resize(500, 50)

App = QApplication([])
window = Window()
App.exec()

The problem is that when I want to shrink the window, the static label (left one) is gradually covered by the dynamic label. So, in some cases, only a portion of the left label is available. Is it possible to hide the left label when there is no more space available in the QHBoxLayout for both labels and show it again when there is enough space?

Amir
  • 65
  • 1
  • 2
  • 7
  • Why are you using those size policies? – musicamante Aug 19 '22 at 14:14
  • These size policies are proposed [here](https://stackoverflow.com/questions/21739119/qt-hboxlayout-stop-mainwindow-from-resizing-to-contents) and make it possible to shrink window size by overlapping or cutting off `QLabel`s. But I seek a solution involving hiding/showing rather than overlapping. – Amir Aug 19 '22 at 14:35
  • That doesn't seem a very effective UX choice, did you consider using a scroll area instead? In any case, the only way to do so is to override the `resizeEvent()` of the window (or the central widget using a subclass) or eventually `setGeometry()` of a QBoxLayout subclass and then hide the widget after computing the geometries of the labels (but using a size policy for the first label with [`setRetainSizeWhenHidden(True)`](https://doc.qt.io/qt-6/qsizepolicy.html#setRetainSizeWhenHidden)). – musicamante Aug 19 '22 at 17:47

0 Answers0