import sys
import traceback
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class TabWidget(QTabWidget):
    def __init__(self, parent):
        try:
            super(TabWidget, self).__init__(parent)
            self.init_ui()
            self.init_slot()
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.setTabsClosable(True)  # 可以关闭
            self.setMovable(True)  # 可以交换顺序
        except:
            traceback.print_exc()

    def init_slot(self):
        try:
            self.tabCloseRequested.connect(self.removeTab)
        except:
            traceback.print_exc()

class Main(QDialog):
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.init_ui()
            self.init_slot()
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.resize(720, 480)
            self.setWindowTitle("选项卡控件demo")
            # 初始化tabWidget
            self.tabWidget = TabWidget(self)
            # 定义每个tab页
            self.tab1 = QWidget(self.tabWidget)
            self.tab2 = QWidget(self.tabWidget)
            self.tab3 = QWidget(self.tabWidget)
            # tab页加入tabWidget
            self.tabWidget.addTab(self.tab1, '选项卡1')
            self.tabWidget.addTab(self.tab2, '选项卡2')
            self.tabWidget.addTab(self.tab3, '选项卡3')
            # 布局
            layout = QHBoxLayout()
            layout.addWidget(self.tabWidget)
            self.setLayout(layout)
        except:
            traceback.print_exc()

    def init_slot(self):
        try:
            self.tabWidget.currentChanged.connect(print)
        except:
            traceback.print_exc()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())