pyqtgraph 获取鼠标位置

获取移动鼠标位置,打印出来。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
import pyqtgraph as pg


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # 创建一个pyqtgraph的PlotWidget
        self.plot_widget = pg.PlotWidget()
        self.setCentralWidget(self.plot_widget)  # 中心只有一个plot_widget

        # 连接鼠标移动事件
        self.plot_widget.scene().sigMouseMoved.connect(self.mouse_moved)

    def mouse_moved(self, event):
        # 获取鼠标位置
        # pos = event[0]  # event是一个包含坐标信息的元组,我们只需要第一个元素
        # x = pos.x()
        # y = pos.y()
        x = event.x()
        y = event.y()
        # 输出鼠标位置
        print(f"Mouse position: x={x}, y={y}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

  

获取鼠标左键位置。

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QMouseEvent
import pyqtgraph.opengl as gl


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # 创建一个pyqtgraph的GLViewWidget
        self.view_widget = gl.GLViewWidget()
        self.setCentralWidget(self.view_widget)

        # 关联鼠标左键按下事件到回调函数
        self.view_widget.mousePressEvent = self.mouse_left_button_pressed

    def mouse_left_button_pressed(self, event: QMouseEvent):
        if event.button() == Qt.LeftButton:
            # 获取鼠标位置
            pos = event.pos()
            x = pos.x()
            y = pos.y()

            # 调用回调函数并传递鼠标位置
            self.on_mouse_left_button_pressed(x, y)

    def on_mouse_left_button_pressed(self, x, y):
        # 在这里执行鼠标左键按下的操作
        print(f"Mouse left button pressed at position: x={x}, y={y}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

猜你喜欢

转载自blog.csdn.net/jizhidexiaoming/article/details/131185476