以下是 PyQt4 中 Python 中此类行为的实现。将其转换为 C++ 应该很容易。请注意,Qt5 有一个很好的信号tabBarDoubleClicked,而 Qt4 中没有这个信号。这段代码也创建了这样的信号。
from PyQt4 import QtGui
from PyQt4.QtCore import pyqtSignal, pyqtSlot
class QTabBar(QtGui.QTabBar):
"""QTabBar with double click signal and tab rename behavior."""
def __init__(self, parent=None):
super().__init__(parent)
tabDoubleClicked = pyqtSignal(int)
def mouseDoubleClickEvent(self, event):
tab_index = self.tabAt(event.pos())
self.tabDoubleClicked.emit(tab_index)
self.start_rename(tab_index)
def start_rename(self, tab_index):
self.__edited_tab = tab_index
rect = self.tabRect(tab_index)
top_margin = 3
left_margin = 6
self.__edit = QtGui.QLineEdit(self)
self.__edit.show()
self.__edit.move(rect.left() + left_margin, rect.top() + top_margin)
self.__edit.resize(rect.width() - 2 * left_margin, rect.height() - 2 * top_margin)
self.__edit.setText(self.tabText(tab_index))
self.__edit.selectAll()
self.__edit.setFocus()
self.__edit.editingFinished.connect(self.finish_rename)
@pyqtSlot()
def finish_rename(self):
self.setTabText(self.__edited_tab, self.__edit.text())
self.__edit.deleteLater()
class QTabWidget(QtGui.QTabWidget):
"""QTabWidget with double click on tab signal and tab rename behavior."""
def __init__(self, parent):
super().__init__(parent)
self.setTabBar(QTabBar())
self.tabBar().tabDoubleClicked.connect(self.tabBarDoubleClicked)
tabBarDoubleClicked = pyqtSignal(int)
请注意,在选项卡标题中对齐 qlineedit 有一个相当老套的解决方案。它是通过将边距固定为某个值来实现的。我敢肯定,如有必要,可以在样式中查找该值。