Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 11th, 2012  |  syntax: None  |  size: 1.81 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. PyQt: Editable Tab Labels
  2. from PyQt4 import QtGui, QtCore
  3.  
  4. class TabBar(QtGui.QTabBar):
  5.     def __init__(self, parent):
  6.         QtGui.QTabBar.__init__(self, parent)
  7.         self._editor = QtGui.QLineEdit(self)
  8.         self._editor.setWindowFlags(QtCore.Qt.Popup)
  9.         self._editor.setFocusProxy(self)
  10.         self._editor.editingFinished.connect(self.handleEditingFinished)
  11.         self._editor.installEventFilter(self)
  12.  
  13.     def eventFilter(self, widget, event):
  14.         if ((event.type() == QtCore.QEvent.MouseButtonPress and
  15.              not self._editor.geometry().contains(event.globalPos())) or
  16.             (event.type() == QtCore.QEvent.KeyPress and
  17.              event.key() == QtCore.Qt.Key_Escape)):
  18.             self._editor.hide()
  19.             return True
  20.         return QtGui.QTabBar.eventFilter(self, widget, event)
  21.  
  22.     def mouseDoubleClickEvent(self, event):
  23.         index = self.tabAt(event.pos())
  24.         if index >= 0:
  25.             self.editTab(index)
  26.  
  27.     def editTab(self, index):
  28.         rect = self.tabRect(index)
  29.         self._editor.setFixedSize(rect.size())
  30.         self._editor.move(self.parent().mapToGlobal(rect.topLeft()))
  31.         self._editor.setText(self.tabText(index))
  32.         if not self._editor.isVisible():
  33.             self._editor.show()
  34.  
  35.     def handleEditingFinished(self):
  36.         index = self.currentIndex()
  37.         if index >= 0:
  38.             self._editor.hide()
  39.             self.setTabText(index, self._editor.text())
  40.  
  41. class Window(QtGui.QTabWidget):
  42.     def __init__(self):
  43.         QtGui.QTabWidget.__init__(self)
  44.         self.setTabBar(TabBar(self))
  45.         self.addTab(QtGui.QWidget(self), 'Tab One')
  46.         self.addTab(QtGui.QWidget(self), 'Tab Two')
  47.  
  48. if __name__ == '__main__':
  49.  
  50.     import sys
  51.     app = QtGui.QApplication(sys.argv)
  52.     window = Window()
  53.     window.show()
  54.     sys.exit(app.exec_())