Displaying tooltips in PyQT for a QTreeView item

2019-07-21 04:42发布

问题:

I have followed some useful online tutorials by Yasin Uludag to experiment with PyQt (or rather PySide) to create a simple tree view, but I'm having problems with getting tooltips to work. In the following code, the tooltip text is displayed on the console rather than in a tooltip window. All the other examples I have seen use setToolTip directly on the widget item, but I don't think I have direct access to that in this Model/View approach. Is there some initialization I need to do on the QTreeView itself?

 class TreeModel(QtCore.QAbstractItemModel):

     def __init__(self, root, parent=None):
         super(NXTreeModel, self).__init__(parent)
         self._rootNode = root

     def data(self, index, role):

          node = index.internalPointer()

         if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
             return node.name()

         if role == QtCore.Qt.ToolTipRole:
             return node.keys()

回答1:

It worked like below code.

class TreeModel(QAbstractItemModel):
    ...
    def data(self, index, role=Qt.DisplayRole):
        ...
        if role == Qt.ToolTipRole:
            return 'ToolTip'

    def flags(self, index):
        if not index.isValid():
            return Qt.NoItemFlags # 0
        return Qt.ItemIsSelectable # or Qt.ItemIsEnabled


回答2:

You have to enable the ToolTip role

class TreeModel(QtCore.QAbstractItemModel):
    ...

    def flags(self, index):
        if not index.isValid():
            return 0
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled |\
               QtCore.Qt.ItemIsSelectable | QtCore.Qt.ToolTip


标签: pyqt tooltip