PyQt5:使用QTabWidget :: tabInserted(int index)检测新插入的选项卡

时间:2018-10-13 15:10:36

标签: pyqt5

我是PyQt5的新手。我制作了一个tabWidget,可以在其中连接按钮以动态添加选项卡并删除/关闭它们。在插入带有按钮的选项卡之前。单击该选项卡时,有一个打开的(已插入)选项卡显示“没有选项卡处于打开状态”。我想在插入新标签后关闭此标签,并在关闭所有新标签后重新打开标签(当没有标签打开时)。我找不到如何使用http://doc.qt.io/qt-5/qtabwidget.html中的QTabWidget :: tabInserted(int index)的任何示例。有谁知道如何使用tabInserted和tabRemoved来检测触发时。我想每次插入选项卡时增加,而在删除选项卡时减少,以了解何时有打开的选项卡而没有打开的选项卡。谢谢

self.toolButton.clicked.connect(self.button_addtab)
self.tabWidget.tabCloseRequested.connect(self.close_tab)

def button_addtab(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, "")
        self.tabWidget.setCurrentIndex(pages-0)
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Second_tab"))


def close_tab(self, index):
        self.tabWidget.removeTab(index)

我尝试过:

if self.tabWidget.count() <= 0:
          #Add the "no tab open" tab  
            self.tab_3 = QtWidgets.QWidget()
            self.tab_3.setObjectName("tab_3")
            self.tabWidget.addTab(self.tab_3, "")
            _translate = QtCore.QCoreApplication.translate
            self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Info"))
elif self.tabWidget.count() > 0:
            self.tabWidget.removeTab(self.tabWidget.indexOf(self.tab_3))

这项工作,但是在关闭后不会添加,在添加了另一个标签后会重新打开。这就是为什么我想使用tabInserted

1 个答案:

答案 0 :(得分:0)

请参见class TabWidget

import sys
from PyQt5.QtCore    import Qt, QRect
from PyQt5.QtGui     import QColor, QPainter
from PyQt5.QtWidgets import (QApplication, QWidget, QMainWindow, QAction, 
                             QVBoxLayout, QTabWidget, QFileDialog, QPlainTextEdit, QHBoxLayout)

lineBarColor       = QColor(53, 53, 53)       
lineHighlightColor = QColor('#00FF04')        


class TabWidget(QTabWidget):

    def __init__(self, parent=None):
        super(TabWidget, self).__init__(parent)

    # This virtual handler is called after a tab was removed from position index.   
    def tabRemoved(self, index):
        print("\n tab was removed from position index -> {}".format(index))

    # This virtual handler is called after a new tab was added or inserted at position index.        
    def tabInserted(self, index):
        print("\n New tab was added or inserted at position index -> {}".format(index))



class NumberBar(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.editor = parent
        layout      = QVBoxLayout(self)
        self.editor.blockCountChanged.connect(self.update_width)
        self.editor.updateRequest.connect(self.update_on_scroll)
        self.update_width('001')   

    def mousePressEvent(self, QMouseEvent):
        print("\n - class NumberBar(QWidget): \n\tdef mousePressEvent(self, QMouseEvent):")

    def update_on_scroll(self, rect, scroll):
        if self.isVisible():
            if scroll:
                self.scroll(0, scroll)
            else:
                self.update()

    def update_width(self, string):
        width = self.fontMetrics().width(str(string)) + 10
        if self.width() != width:
            self.setFixedWidth(width)

    def paintEvent(self, event):
        if self.isVisible():
            block   = self.editor.firstVisibleBlock()
            height  = self.fontMetrics().height()
            number  = block.blockNumber()
            painter = QPainter(self)
            painter.fillRect(event.rect(), lineBarColor)
            painter.setPen(Qt.white)                       
            painter.drawRect(0, 0, event.rect().width() - 1, event.rect().height() - 1)
            font = painter.font()

            current_block = self.editor.textCursor().block().blockNumber() + 1

            while block.isValid():
                block_geometry = self.editor.blockBoundingGeometry(block)
                offset = self.editor.contentOffset()
                block_top = block_geometry.translated(offset).top()
                number += 1

                rect = QRect(0, block_top, self.width() - 5, height)

                if number == current_block:
                    font.setBold(True)
                else:
                    font.setBold(False)

                painter.setFont(font)
                painter.drawText(rect, Qt.AlignRight, '%i' % number)

                if block_top > event.rect().bottom():
                    break

                block = block.next()

            painter.end()


class Content(QWidget):
    def __init__(self, text):
        super(Content, self).__init__()
        self.editor = QPlainTextEdit()
        self.editor.setPlainText(text)
        # Create a layout for the line numbers
        self.hbox    = QHBoxLayout(self)
        self.numbers = NumberBar(self.editor)
        self.hbox.addWidget(self.numbers)
        self.hbox.addWidget(self.editor)


class MyTableWidget(QWidget):

    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)

        self.layout = QVBoxLayout(self)
        # Initialize tab screen
        self.tabs = TabWidget()     #QTabWidget()
        self.tabs.resize(300, 200)

        # Add tabs
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.closeTab)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def closeTab(self, index):
        tab = self.tabs.widget(index)
        tab.deleteLater()
        self.tabs.removeTab(index)

    def addtab(self, content, fileName):
        self.tabs.addTab(Content(str(content)), str(fileName))


class Main(QMainWindow):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.open()
        self.tabs = MyTableWidget()
        self.setCentralWidget(self.tabs)
        self.initUI()
        self.show()

    def initUI(self):
        self.statusBar()
        menu = self.menuBar()
        fileMenu = menu.addMenu('File')
        fileMenu.addAction(self.openAct)
        self.resize(800, 600)

    def closeTab(self, index):
        tab = self.tabs.widget(index)
        tab.deleteLater()
        self.tabs.removeTab(index)

    def buttonClicked(self):
        self.tabs.addTab(Content("smalltext2"), "sadsad")

    def open(self):
        self.openAct = QAction('Open...', self)
        self.openAct.setShortcut('Ctrl+O')
        self.openAct.setStatusTip('Open a file')
        self.is_opened = False
        self.openAct.triggered.connect(self.openFile)

    def openFile(self):                                   
        options = QFileDialog.Options()
        filenames, _ = QFileDialog.getOpenFileNames(
            self, 'Open a file', '',
            'Python Files (*.py);;Text Files (*.txt)',
            options=options
        )
        if filenames:
            for filename in filenames:
                with open(filename, 'r+') as file_o:
                    try: 
                        text = file_o.read()
                        self.tabs.addtab(text, filename)      
                    except Exception as e:
                        print("Error: filename=`{}`, `{}` ".format( filename, str(e)))


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

enter image description here