Skip to content

Instantly share code, notes, and snippets.

@mcho421-snippets
Created October 24, 2012 00:10
Show Gist options
  • Save mcho421-snippets/3942838 to your computer and use it in GitHub Desktop.
Save mcho421-snippets/3942838 to your computer and use it in GitHub Desktop.
Python: PyQt: Editable Tab Labels
# http://stackoverflow.com/questions/8707457/pyqt-editable-tab-labels
from PyQt4 import QtGui, QtCore
class TabBar(QtGui.QTabBar):
def __init__(self, parent):
QtGui.QTabBar.__init__(self, parent)
self._editor = QtGui.QLineEdit(self)
self._editor.setWindowFlags(QtCore.Qt.Popup)
self._editor.setFocusProxy(self)
self._editor.editingFinished.connect(self.handleEditingFinished)
self._editor.installEventFilter(self)
def eventFilter(self, widget, event):
if ((event.type() == QtCore.QEvent.MouseButtonPress and
not self._editor.geometry().contains(event.globalPos())) or
(event.type() == QtCore.QEvent.KeyPress and
event.key() == QtCore.Qt.Key_Escape)):
self._editor.hide()
return True
return QtGui.QTabBar.eventFilter(self, widget, event)
def mouseDoubleClickEvent(self, event):
index = self.tabAt(event.pos())
if index >= 0:
self.editTab(index)
def editTab(self, index):
rect = self.tabRect(index)
self._editor.setFixedSize(rect.size())
self._editor.move(self.parent().mapToGlobal(rect.topLeft()))
self._editor.setText(self.tabText(index))
if not self._editor.isVisible():
self._editor.show()
def handleEditingFinished(self):
index = self.currentIndex()
if index >= 0:
self._editor.hide()
self.setTabText(index, self._editor.text())
class Window(QtGui.QTabWidget):
def __init__(self):
QtGui.QTabWidget.__init__(self)
self.setTabBar(TabBar(self))
self.addTab(QtGui.QWidget(self), 'Tab One')
self.addTab(QtGui.QWidget(self), 'Tab Two')
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment