Подтвердить что ты не робот

Как добавить кнопку "новая вкладка" рядом с вкладками QMdiArea в режиме просмотра с вкладками?

Я бы хотел иметь кнопку "новая вкладка", как у Chrome или Firefox для моего QMdiArea.

Я могу сделать кнопку или пункт меню где-то, что добавляет новый субдокумент в MDI, но как я могу сделать его привлекательной привлекательной вкладкой с меткой "+"? В качестве альтернативы, я был бы достаточно счастлив с помощью QTabWidget с такой кнопкой.

4b9b3361

Ответ 1

Вам нужно будет написать свой собственный класс для QTabBar. Кнопка "плюс" может быть добавлена ​​с помощью абсолютного позиционирования.

У меня есть код для PySide; это должно дать вам основную идею.

class TabBarPlus(QtGui.QTabBar):
    """Tab bar that has a plus button floating to the right of the tabs."""

    plusClicked = QtCore.Signal()

    def __init__(self):
        super().__init__()

        # Plus Button
        self.plusButton = QtGui.QPushButton("+")
        self.plusButton.setParent(self)
        self.plusButton.setFixedSize(20, 20)  # Small Fixed size
        self.plusButton.clicked.connect(self.plusClicked.emit)
        self.movePlusButton() # Move to the correct location
    # end Constructor

    def sizeHint(self):
        """Return the size of the TabBar with increased width for the plus button."""
        sizeHint = QtGui.QTabBar.sizeHint(self) 
        width = sizeHint.width()
        height = sizeHint.height()
        return QtCore.QSize(width+25, height)
    # end tabSizeHint

    def resizeEvent(self, event):
        """Resize the widget and make sure the plus button is in the correct location."""
        super().resizeEvent(event)

        self.movePlusButton()
    # end resizeEvent

    def tabLayoutChange(self):
        """This virtual handler is called whenever the tab layout changes.
        If anything changes make sure the plus button is in the correct location.
        """
        super().tabLayoutChange()

        self.movePlusButton()
    # end tabLayoutChange

    def movePlusButton(self):
        """Move the plus button to the correct location."""
        # Find the width of all of the tabs
        size = sum([self.tabRect(i).width() for i in range(self.count())])
        # size = 0
        # for i in range(self.count()):
        #     size += self.tabRect(i).width()

        # Set the plus button location in a visible area
        h = self.geometry().top()
        w = self.width()
        if size > w: # Show just to the left of the scroll buttons
            self.plusButton.move(w-54, h)
        else:
            self.plusButton.move(size, h)
    # end movePlusButton
# end class MyClass

class CustomTabWidget(QtGui.QTabWidget):
    """Tab Widget that that can have new tabs easily added to it."""

    def __init__(self):
        super().__init__()

        # Tab Bar
        self.tab = TabBarPlus()
        self.setTabBar(self.tab)

        # Properties
        self.setMovable(True)
        self.setTabsClosable(True)

        # Signals
        self.tab.plusClicked.connect(self.addTab)
        self.tab.tabMoved.connect(self.moveTab)
        self.tabCloseRequested.connect(self.removeTab)
    # end Constructor
# end class CustomTabWidget

Ответ 2

Я знаю, что этот вопрос устарел, но некоторое время назад я искал готовые к использованию функции, которые вы запросили. Я немного вычислил и реализовал это для Qt 5 - взглянуть на репо.

Основная идея:

// Create button what must be placed in tabs row
QToolButton *tb = new QToolButton();
tb->setText("+");
// Add empty, not enabled tab to tabWidget
tabWidget->addTab(new QLabel("Add tabs by pressing \"+\""), QString());
tabWidget->setTabEnabled(0, false);
// Add tab button to current tab. Button will be enabled, but tab -- not
tabWidget->tabBar()->setTabButton(0, QTabBar::RightSide, tb);

Ответ 3

Почему бы не сделать кнопку из последней вкладки вашего QTabWidget? Просто создайте последнюю вкладку с символом "+" на ней и используйте событие currentChanged.

class Trace_Tabs(QTabWidget):

    def __init__(self):
        QTabWidget.__init__(self)       
        self._build_tabs()

    def _build_tabs(self):
        self.setUpdatesEnabled(True)

        self.insertTab(0,QWidget(), "Trace" )
        self.insertTab(1,QWidget(),'  +  ') 

        self.currentChanged.connect(self._add_trace) 

    def _add_trace(self, index):    

        if index == self.count()-1 :    
            '''last tab was clicked. add tab'''
            self.insertTab(index, QWidget(), "Trace %d" %(index+1)) 
            self.setCurrentIndex(index)

if __name__ == '__main__':    
    app = QApplication([])    
    tabs = Trace_Tabs()
    tabs.show()    
    app.exec_()

Ответ 4

Аналогичная концепция для ответа @Garjy:

Вы можете использовать "пустую" вкладку и добавить кнопку на эту вкладку. Это также заменит кнопку "закрыть", если вы используете TabWidget.setTabsCloseable(True). Это можно сделать на "пустой" вкладке, поэтому я предлагаю комбинировать с ответом @Garjy или добавлять текст/другую новую кнопку.

import sys
from qtpy.QtWidgets import QTabWidget, QWidget, QToolButton, QTabBar, QApplication

class Trace_Tabs(QTabWidget):

    def __init__(self):
        QTabWidget.__init__(self)
        self.setTabsClosable(True)
        self._build_tabs()

    def _build_tabs(self):

        self.insertTab(0, QWidget(), "Trace 0" )

        # create the "new tab" tab with button
        self.insertTab(1, QWidget(),'')
        nb = self.new_btn = QToolButton()
        nb.setText('+') # you could set an icon instead of text
        nb.setAutoRaise(True)
        nb.clicked.connect(self.new_tab)
        self.tabBar().setTabButton(1, QTabBar.RightSide, nb)

    def new_tab(self):
        index = self.count() - 1
        self.insertTab(index, QWidget(), "Trace %d" % index)
        self.setCurrentIndex(index)

if __name__ == '__main__':

    app = QApplication(sys.argv)

    tabs = Trace_Tabs()
    tabs.show()

    app.exec_()