【问题标题】:Inline renaming of a tab in QTabBar/QTabWidgetQTabBar/QTabWidget 中标签的内联重命名
【发布时间】:2015-05-15 21:29:55
【问题描述】:

我真的想要一个可以通过双击标签标题来重命名的 QTabWidget。 我在谷歌上搜索并找到了this solution,但这更像是一个开发人员的大纲,他们知道自己如何通过 Qt 并将其子类化为小部件。 我有点卡住如何实现这一切。我使用了example given further down that thread(与IndependentLineEdit 等等)并且它有效,但这不是我想要的。 我不想有任何类型的 InputDialog。我不想有任何浮动小部件或其他东西。 我基本上想要的是使用 QTabWidget(子类),其行为方式与现代办公套件中的电子表格选项卡类似 - 例如,选项卡标签被无缝线编辑取代,它在 Enter 上重置选项卡标签或在 Esc 上保持完整。 到目前为止,我还没有找到这样的解决方案。我明白我真正需要的是非常接近这个:

在 QTabBar::tabRect() 提供一个临时的 QLineEdit 填充 QTabBar::tabText()

但我不明白该怎么做。此外,由于 QTabBar 是一种裸标签栏,我也希望将其包含在 QTabWidget(子类)中。

【问题讨论】:

    标签: c++ qt qtabwidget qtabbar


    【解决方案1】:

    以下是 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 有一个相当老套的解决方案。它是通过将边距固定为某个值来实现的。我敢肯定,如果需要,可以在样式中查找该值。

    【讨论】:

    • 哇,这似乎正是我所需要的 :) 谢谢。我会尽快将其转换为 C++ :) 你介意我在有工作 C++ 解决方案时编辑你的答案吗?
    • 完全没有,请继续。
    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多