1、创建一个窗口,内部有一个label控件,鼠标移入窗口时,让label位置跟随鼠标位置,鼠标设置为指定图标。
①:鼠标在窗口内部移动,首先设置在窗口内部的鼠标跟踪。
②:需要自定义类,继承父类,重写鼠标移动事件,通过在父控件种查找子控件方法,去查找label
import sys
from PyQt5.Qt import *
class Window(QWidget):
def mouseMoveEvent(self, mv):
print("鼠标移动", mv.localPos())
# 应用在父控件中查找子控件的方法,则可查到label控件
label = self.findChild(QLabel)
label.move(mv.localPos().x(), mv.localPos().y())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.setWindowTitle("鼠标操作案例")
window.resize(500, 500)
window.move(500, 200)
# 设置鼠标跟踪之后会调用window内部的mouseMoveEvent事件
window.setMouseTracking(True)
pixmap = QPixmap(r"C:\Users\22104\Desktop\OIP-C.jpg").scaled(20, 20)
cursor = QCursor(pixmap)
window.setCursor(cursor)
label = QLabel(window)
label.setText("鼠标鼠标")
label.move(100, 100)
label.setStyleSheet("background-color:cyan")
window.show()
sys.exit(app.exec_())
将上述操作封装为一个类:
import sys
from PyQt5.Qt import *
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("鼠标操作案例")
self.resize(500, 500)
self.move(500, 200)
# 设置鼠标跟踪之后会调用window内部的mouseMoveEvent事件
self.setMouseTracking(True)
pixmap = QPixmap(r"C:\Users\22104\Desktop\OIP-C.jpg").scaled(20, 20)
cursor = QCursor(pixmap)
self.setCursor(cursor)
label = QLabel(self)
self.label = label
label.setText("鼠标鼠标")
label.move(100, 100)
label.setStyleSheet("background-color:cyan")
def mouseMoveEvent(self, mv):
print("鼠标移动", mv.localPos())
# 应用在父控件中查找子控件的方法,则可查到label控件
label = self.findChild(QLabel)
label.move(mv.localPos().x(), mv.localPos().y())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())