如何使用Label跟踪鼠标进入事件

How to track the mouse enter event with Label

下面的代码创建了一个在一行中包含三个标签的小部件。 每次将鼠标置于其中一个标签上时,我希望鼠标光标从默认的 "arrow" 变为 "hand" 图标。如何实现?

class SquareLabel(QLabel):
    def __init__(self, parent=None):
        super(SquareLabel, self).__init__(parent)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(223, 230, 248))
        self.setPalette(p)

    def mousePressEvent(self, event):
        print event


class SuperEdit(QWidget):
    def __init__(self, data, parent=None):
        super(SuperEdit, self).__init__(parent)

        layout = QHBoxLayout()
        layout.setContentsMargins(2, 2, 2, 2)
        self.setLayout(layout)

        for name in data:
            label = SquareLabel(self)
            label.setText(name)
            layout.addWidget(label)


if __name__ == '__main__':
    names = ['Name 1', 'Name 2', 'Name 3']
    app = QApplication([])
    editor = SuperEdit(names)
    editor.show()
    app.exec_()

可以直接在标签class中使用此方法设置游标:

from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt

self.setCursor(QCursor(Qt.PointingHandCursor))

要检测鼠标何时进入小部件,技巧是将setMouseTracking定义为True,然后可以触发事件:

class SquareLabel(QLabel):
    def __init__(self, parent=None):
        super(SquareLabel, self).__init__(parent)
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(223, 230, 248))
        self.setPalette(p)
        self.setMouseTracking(True)

    def mouseMoveEvent(self, event):
        print "On Hover" # event.pos().x(), event.pos().y()

    def mousePressEvent(self, event):
        print event