pyqt5 tabwidget vertical tab horizontal text alignment left

后端 未结 2 1617
夕颜
夕颜 2020-12-15 13:58

Since pyqt doesn\'t have horizontal text in vertical tab option, I followed this link to make it happen. I wanted to have icons on the left and then text after icon and diff

2条回答
  •  独厮守ぢ
    2020-12-15 14:20

    The solution is to use a QProxyStyle to redirect text painting:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    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(QtWidgets.QStyle.CE_TabBarTabShape, opt)
                painter.save()
    
                s = opt.rect.size()
                s.transpose()
                r = QtCore.QRect(QtCore.QPoint(), s)
                r.moveCenter(opt.rect.center())
                opt.rect = r
    
                c = self.tabRect(i).center()
                painter.translate(c)
                painter.rotate(90)
                painter.translate(-c)
                painter.drawControl(QtWidgets.QStyle.CE_TabBarTabLabel, opt);
                painter.restore()
    
    
    class TabWidget(QtWidgets.QTabWidget):
        def __init__(self, *args, **kwargs):
            QtWidgets.QTabWidget.__init__(self, *args, **kwargs)
            self.setTabBar(TabBar(self))
            self.setTabPosition(QtWidgets.QTabWidget.West)
    
    class ProxyStyle(QtWidgets.QProxyStyle):
        def drawControl(self, element, opt, painter, widget):
            if element == QtWidgets.QStyle.CE_TabBarTabLabel:
                ic = self.pixelMetric(QtWidgets.QStyle.PM_TabBarIconSize)
                r = QtCore.QRect(opt.rect)
                w =  0 if opt.icon.isNull() else opt.rect.width() + self.pixelMetric(QtWidgets.QStyle.PM_TabBarIconSize)
                r.setHeight(opt.fontMetrics.width(opt.text) + w)
                r.moveBottom(opt.rect.bottom())
                opt.rect = r
            QtWidgets.QProxyStyle.drawControl(self, element, opt, painter, widget)
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        QtWidgets.QApplication.setStyle(ProxyStyle())
        w = TabWidget()
        w.addTab(QtWidgets.QWidget(), QtGui.QIcon("zoom.png"), "ABC")
        w.addTab(QtWidgets.QWidget(), QtGui.QIcon("zoom-in.png"), "ABCDEFGH")
        w.addTab(QtWidgets.QWidget(), QtGui.QIcon("zoom-out.png"), "XYZ")
    
        w.resize(640, 480)
        w.show()
    
        sys.exit(app.exec_())
    

提交回复
热议问题