My PyQt application includes a QHBoxLayout
which contains two QLabel
s, 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?