简介:
接上一篇文章:
自定义titlebar组件
这个就是titlebar
设计思路:
基类 TitleBar 完成布局, 以及 关闭,缩小,放大基本功能的实现。子类在hBoxLayout布局属性上,插入新的组件。
横向布局:
self.hBoxLayout.setSpacing(0)
self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
self.hBoxLayout.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
self.hBoxLayout.addStretch(1)
self.hBoxLayout.addWidget(self.minBtn, 0, Qt.AlignRight)
self.hBoxLayout.addWidget(self.maxBtn, 0, Qt.AlignRight)
self.hBoxLayout.addWidget(self.closeBtn, 0, Qt.AlignRight)
qwidget setFixedHeight
设置固定高度
setFixedSize
设置固定大小
setStyleSheet
qss样式
QHBoxLayout
setSpacing
设置组件间距
setContentsMargins
设置margins
setAlignment
设置组件对齐方式
addStretch
添加空盒子
addWidget(self, a0: QWidget, stretch: int = 0, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment())
给布局添加组件。
insertSpacing(self, index: int, size: int)
插入间距 index组件索引 从0开始。 size:间距
insertWidget(1, self.iconLabel, 0, Qt.AlignLeft)
参数 : 插入索引位置 组件 stretch 对齐方式
class StandardTitleBar(TitleBar):
""" Title bar with icon and title """
def __init__(self, parent):
super().__init__(parent)
# add window icon
self.iconLabel = QLabel(self)
self.iconLabel.setFixedSize(20, 20)
self.hBoxLayout.insertSpacing(0, 10)
self.hBoxLayout.insertWidget(1, self.iconLabel, 0, Qt.AlignLeft)
self.window().windowIconChanged.connect(self.setIcon)
# add title label
self.titleLabel = QLabel(self)
self.hBoxLayout.insertWidget(2, self.titleLabel, 0, Qt.AlignLeft)
self.titleLabel.setStyleSheet("""
QLabel{
background: transparent;
font: 13px 'Segoe UI';
padding: 0 4px
}
""")
self.window().windowTitleChanged.connect(self.setTitle)
def setTitle(self, title):
""" set the title of title bar
Parameters
----------
title: str
the title of title bar
"""
self.titleLabel.setText(title)
self.titleLabel.adjustSize()
def setIcon(self, icon):
""" set the icon of title bar
Parameters
----------
icon: QIcon | QPixmap | str
the icon of title bar
"""
self.iconLabel.setPixmap(QIcon(icon).pixmap(20, 20))
总结:
不是一种很好的设计,因为子类需要调用insertWidget ,来插入组件实现更多功能。必须要读了父类,才知道 inserWidget 插入的索引位置。
不过好在简单。