I want to make a sidebar in my GUI using QT5 and python bindings. In my sidebar, I use a QVBoxLayout to add tiles that consist of an icon of fixed height, and a variable sized text.
I have a display problem that I am unable to fix. See the follwing screenshot. I have added borders to show the problem.
from qtpy.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy
from qtpy.QtCore import Qt, QSize
from scrutiny.gui.dashboard_components.base_component import ScrutinyGUIBaseComponent
from typing import List, Type
class Sidebar(QWidget):
SIDEBAR_ELEMENT_W = 64
SIDEBAR_W = SIDEBAR_ELEMENT_W + 12
SIDEBAR_ELEMENT_ICON_H = 48
_components:List[Type[ScrutinyGUIBaseComponent]]
def __init__(self, components:List[Type[ScrutinyGUIBaseComponent]]) -> None:
super().__init__()
self.setFixedWidth(self.SIDEBAR_W)
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding))
sidebar_layout = QVBoxLayout(self)
sidebar_layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignVCenter)
sidebar_margin = (self.SIDEBAR_W - self.SIDEBAR_ELEMENT_W)//2
sidebar_layout.setContentsMargins(sidebar_margin,20,sidebar_margin,0)
sidebar_layout.setSpacing(0)
self._components = components.copy()
self.timers = []
for component in self._components:
sidebar_element = QWidget()
sidebar_element.setProperty('class', 'sidebar_element')
element_layout = QVBoxLayout(sidebar_element)
element_layout.setSpacing(0)
element_layout.setContentsMargins(0,5,0,5)
sidebar_element.setMaximumWidth(self.SIDEBAR_ELEMENT_W)
icon_label = QLabel()
icon = component.get_icon()
icon_label.setFixedHeight(self.SIDEBAR_ELEMENT_ICON_H)
icon_label.setPixmap(icon.scaled(QSize(icon_label.width(), icon_label.height()), Qt.AspectRatioMode.KeepAspectRatio))
text = QLabel(component.get_name(), sidebar_element)
text.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignCenter)
text.setWordWrap(True)
text.setStyleSheet("border:1px solid blue")
element_layout.addWidget(icon_label)
element_layout.addWidget(text)
sidebar_layout.addWidget(sidebar_element)
As we can see, when the text label span on more than one line, the block grows upward and overlaps the icon. I tried lots of settings and I either end up cropping the second line or stretching the element down to the very bottom of the window.
Any help would be appreciated.