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

时间:2017-07-30 19:56:14

标签: python pyqt qt4 qt5

下面的代码创建了一个小部件,其中一行包含三个标签。 每当鼠标放在其中一个标签上时,我希望鼠标光标从默认的“箭头”变为“手”图标。如何实现呢?

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

1 个答案:

答案 0 :(得分:2)

您可以直接在label类中使用此方法来设置游标:

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