While I was toying and trying some ideas I found out how to create tab bars with Qt that are only visible if you have more than one tab. This is quite popular in browser for example. So without further ado, here's the code:
from PyQt4 import QtGui class TabWidget(QtGui.QTabWidget): def __init__(self, parent=None): super (TabWidget, self).__init__(parent) self.setTabsClosable(True) self.tabCloseRequested.connect(self.removeTab) def tabInserted(self, index): self.tabBar().setVisible(self.count() > 1) def tabRemoved(self, index): self.tabBar().setVisible(self.count() > 1)As you can see, it isn't rocket science. I did some googling but couldn't find anything about it, that's why I want to share my findings. The magic is to only hide the TabBar associated with the TabWidget, not the TabWidget itself.
You can use the following snippet to see the TabWidget in action:
import sys from PyQt4 import QtGui class TabWidget(QtGui.QTabWidget): def __init__(self, parent=None): super (TabWidget, self).__init__(parent) self.setTabsClosable(True) self.tabCloseRequested.connect(self.removeTab) def tabInserted(self, index): self.tabBar().setVisible(self.count() > 1) def tabRemoved(self, index): self.tabBar().setVisible(self.count() > 1) qApp = QtGui.QApplication(sys.argv) tab = TabWidget() button = QtGui.QPushButton('Hello') @button.clicked.connect def clicked(): tab.addTab(QtGui.QLabel('Hello'), 'Hello') tab.addTab(button, 'Button') layout = QtGui.QHBoxLayout() layout.addWidget(tab) window = QtGui.QWidget() window.setLayout(layout) window.resize(600, 400) window.show() qApp.exec_()
Couldnt get this to work with PyQT 4.7.2. Searched around a bit and got this to work:
ReplyDeleteclass TabWidget(QtGui.QTabWidget):
def __init__(self, parent=None):
super (TabWidget, self).__init__(parent)
self.setTabsClosable(True)
self.connect(self, QtCore.SIGNAL('tabCloseRequested(int)'), self.closeTab)
def closeTab(self, idx):
self.removeTab(idx)
Wonderful Post... thanks a Lot...
ReplyDelete