N. Berg
N. Berg

Reputation: 79

PyQt5 adding add and remove widget buttons beside every tab

I want to add buttons to the tabs in the QTabWidget.

My first instinct was to try to get the position of each tab and then add the button ontop of the tab, but I cant figure out how to get the position of the tab! Only the entire tab widget.

b

I was looking around and now what I think I should do is make a custom TabBar class where I can place buttons on each tab like the standard Qt close button.

Anyone here who can send me in the right direction?

Upvotes: 2

Views: 3558

Answers (1)

N. Berg
N. Berg

Reputation: 79

Okay so I found out how to make it work like I want it. It was actually quite simple, I made a QWidget class with a horizontal layout and two buttons and passed it to the setTabButton function. For anyone interested see the code below.

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow


class TabExample(QMainWindow):
    def __init__(self):
        super(TabExample, self).__init__()
        self.setWindowTitle("Tab example")

        # Create widgets
        self.tab_widget = QtWidgets.QTabWidget()
        self.setCentralWidget(self.tab_widget)

        # Label's to fill widget
        self.label1 = QtWidgets.QLabel("Tab 1")
        self.label2 = QtWidgets.QLabel("Tab 2")

        # Adding tab's
        self.tab_widget.addTab(self.label1, "Tab 1")
        self.tab_widget.addTab(self.label2, "Tab 2")

        # Tab button's
        self.right = self.tab_widget.tabBar().RightSide
        self.tab_widget.tabBar().setTabButton(0, self.right, TabButtonWidget())
        self.tab_widget.tabBar().setTabButton(1, self.right, TabButtonWidget())

        # Tab settings
        self.tab_widget.tabBar().setMovable(True)

        self.show()


class TabButtonWidget(QtWidgets.QWidget):
    def __init__(self):
        super(TabButtonWidget, self).__init__()
        # Create button's
        self.button_add = QtWidgets.QPushButton("+")
        self.button_remove = QtWidgets.QPushButton("-")

        # Set button size
        self.button_add.setFixedSize(16, 16)
        self.button_remove.setFixedSize(16, 16)

        # Create layout
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(0, 0, 0, 0)

        # Add button's to layout
        self.layout.addWidget(self.button_add)
        self.layout.addWidget(self.button_remove)

        # Use layout in widget
        self.setLayout(self.layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    gui = TabExample()
    sys.exit(app.exec_())

Upvotes: 5

Related Questions