[Python] Make a mouse-slide border between the tab bar and the contents of the tab

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I want to make a QTabWidget with horizontal tabs placed on the left, so that you can change the width of the tab bar with the mouse. To do this, I placed the qtabwidget on the right panel of the qsplitter, and the tabbar from this widget on the left. In general, everything works. But! In QTabWidget, a place is allocated for the tab bar, which is drawn elsewhere. I'm asking for help on how to change the behavior of QTabWidget so that it doesn't have a place for the tab bar. I've been thinking about what to write in the paintEvent method. I even got into the Qt source code, but I didn't figure it out, I just figured out that QStackedWidget is used to store widgets, but it can't be extracted outside.

    import sys
    from PySide2.QtWidgets import (
    QApplication,
    QMainWindow,
    QSplitter,
    QLabel,
    QTabWidget,
    QTabBar,
    QStylePainter,
    )
    from PySide2 import QtWidgets
    from PySide2 import QtCore
    from PySide2 import QtGui
    from PySide2.QtGui import QPainter, QPaintEvent
    from PySide2.QtWidgets import QProxyStyle, QStyle


    class TabBar(QTabBar):
    def tabSizeHint(self, index):
    s = 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)


    if __name__ == "__main__":
    app = QApplication()
    mainwindow = QMainWindow()
    splitter = QSplitter()
    tab_widget = TabWidget()
    tab_widget.addTab(QLabel("Tab one"), "Tab one")
    tab_widget.addTab(QLabel("Tab two"), "Tab two tab two")
    l_widget = QtWidgets.QWidget()
    l_layaout = QtWidgets.QVBoxLayout()
    l_widget.setLayout(l_layaout)
    l_layaout.addWidget(tab_widget.tabBar())
    splitter.addWidget(l_widget)
    splitter.addWidget(tab_widget)
    mainwindow.setCentralWidget(splitter)
    mainwindow.showMaximized()
    sys.exit(app.exec_())



    Or maybe there is another way to make a border that can be changed with the mouse.

    Continue reading...

Compartilhe esta Página