PyQt5:无需ProxyStyle类实现左侧标签页名称左对齐
PyQt5实现左侧水平标签页并左对齐标签文本(无需ProxyStyle)
PyQt5默认情况下,左侧标签页的标签是垂直排列的。现有代码可实现左侧水平标签,但标签名称为居中对齐。无需使用ProxyStyle类即可实现标签名称左对齐,具体修改如下:

修改后的完整代码
from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class TabWidget(QtWidgets.QTabWidget): def __init__(self): QtWidgets.QTabWidget.__init__(self) self.setTabBar(self.TabBar(self)) self.setTabPosition(QTabWidget.TabPosition.West) class TabBar(QtWidgets.QTabBar): def tabSizeHint(self, index): s = QtWidgets.QTabBar.tabSizeHint(self, index) s.transpose() return s def paintEvent(self, event): painter = QtWidgets.QStylePainter(self) opt = QtWidgets.QStyleOptionTab() for i in range(self.count()): self.initStyleOption(opt, i) # 绘制标签形状 painter.drawControl(QStyle.ControlElement.CE_TabBarTabShape, opt) painter.save() tab_rect = self.tabRect(i) # 构造文本绘制矩形:适配文本高度,宽度取标签的高度(因转置后方向变化) text_rect = QtCore.QRect( tab_rect.left(), tab_rect.top(), tab_rect.height(), opt.fontMetrics.height() ) # 让文本矩形在标签内垂直居中 text_rect.moveCenter(tab_rect.center()) # 旋转坐标系,使文本水平显示 painter.translate(tab_rect.center()) painter.rotate(90) painter.translate(-tab_rect.center()) # 设置文本左对齐,并更新绘制矩形 opt.rect = text_rect opt.alignment = Qt.AlignLeft | Qt.AlignVCenter # 绘制标签文本 painter.drawControl(QStyle.ControlElement.CE_TabBarTabLabel, opt) painter.restore() if __name__ == '__main__': app = QApplication([]) tab = TabWidget() tab.setGeometry(0, 0, 800, 600) tab.addTab(QWidget(), "Tab with a long name") tab.addTab(QWidget(), "Tab 2") tab.show() sys.exit(app.exec())
修改说明
- 调整文本绘制矩形:不再使用居中的转置矩形,而是根据标签原始矩形构造适配文本高度的矩形,并保持垂直居中。
- 设置文本对齐方式:通过
opt.alignment = Qt.AlignLeft | Qt.AlignVCenter强制文本左对齐,同时保持垂直居中。 - 坐标系旋转逻辑保留:确保文本水平显示的核心逻辑不变,仅调整文本的绘制位置和对齐规则。
内容的提问来源于stack exchange,提问作者Oleg Palamarchuk
相关产品推荐
相关产品推荐

