I was wondering how to create (using PyQt4) a derived QTabWidget
with a check box next to each tab title? Like this:
Asked
Active
Viewed 3,011 times
4

Lev Levitsky
- 63,701
- 20
- 147
- 175

Jib
- 391
- 1
- 3
- 9
2 Answers
9
Actually I chose to only subclass QTabWidget.
The checkBox is added at the creation of a new tab and saved to a list in order to get its index back.
setCheckState/isChecked methods are intended to control the state of each checkBox specified by its tab index.
Finally, the "stateChanged(int)" signal is captured and remitted with an extra parameter specifying the index of the checkBox concerned.
class CheckableTabWidget(QtGui.QTabWidget):
checkBoxList = []
def addTab(self, widget, title):
QtGui.QTabWidget.addTab(self, widget, title)
checkBox = QtGui.QCheckBox()
self.checkBoxList.append(checkBox)
self.tabBar().setTabButton(self.tabBar().count()-1, QtGui.QTabBar.LeftSide, checkBox)
self.connect(checkBox, QtCore.SIGNAL('stateChanged(int)'), lambda checkState: self.__emitStateChanged(checkBox, checkState))
def isChecked(self, index):
return self.tabBar().tabButton(index, QtGui.QTabBar.LeftSide).checkState() != QtCore.Qt.Unchecked
def setCheckState(self, index, checkState):
self.tabBar().tabButton(index, QtGui.QTabBar.LeftSide).setCheckState(checkState)
def __emitStateChanged(self, checkBox, checkState):
index = self.checkBoxList.index(checkBox)
self.emit(QtCore.SIGNAL('stateChanged(int, int)'), index, checkState)
This is maybe not the perfect way to do things, but at least it remains pretty simple and covers all my needs.

Refugnic Eternium
- 4,089
- 1
- 15
- 24

Jib
- 391
- 1
- 3
- 9
2
The best approach would be to
- Create a custom TabBar, CheckedTabBar (inheriting
QTabBar
) - Create a custom TabWidget, CheckedTabWidget (inheriting
QTabWidget
) - Add a way to test if a tab is checked or not, and maybe some signals when the checkbox is toggled :)
You should set your custom tabbar in the checkedtabwidget constructor, like this:
CheckedTabWidget::CheckedTabWidget(QWidget* parent) : QTabWidget(parent)
{
setTabBar(new CheckedTabBar(this));
}

gnud
- 77,584
- 5
- 64
- 78
-
1You'll have to implement your own tab bar that places a checkbox by the title. – gnud Apr 29 '11 at 07:43
-
Thank you! I posted my code below in case it interests others. – Jib May 07 '11 at 11:05