alphanumeric
alphanumeric

Reputation: 19329

How to track the mouse enter event with Label

The code below creates a single widget with three labels in one line. I would like the mouse cursor to change from a default "arrow" to a "hand" icon every time the mouse is positioned over one of the labels. How to achieve it?

enter image description here

enter image description here

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_()

Upvotes: 2

Views: 4159

Answers (1)

PRMoureu
PRMoureu

Reputation: 13317

You can use this method directly in the label class to set a cursor:

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

self.setCursor(QCursor(Qt.PointingHandCursor))

To detect when the mouse enter a widget, the trick is to define setMouseTracking to True, then the event can be triggered :

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

Upvotes: 4

Related Questions