pyqtgraph 获取鼠标位置

该代码示例展示了如何在PyQt5应用中使用pyqtgraph库来跟踪鼠标移动和左键点击的位置。通过连接鼠标移动事件和左键按下事件,程序可以在控制台打印出鼠标的坐标信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

<think>我们正在讨论如何获取鼠标位置坐标。根据引用[1][2][3][4][5],我们可以从不同技术栈中获取鼠标坐标。用户要求提供完整代码示例,并且特别提到“在UI中获取鼠标位置坐标”。由于用户之前的问题是关于C#WindowsForms的,但引用中涉及多种技术(JavaRobot、Vue3、PyQt5、PowerShell、Unity),我们需要明确用户的技术场景。然而,用户没有指定具体技术,因此我们将提供几种常见UI框架的解决方案。根据用户上一次问题(C#WindowsForms)和本次引用[1](Java)[2](Vue3)[3](PyQt5)[4](PowerShell)[5](Unity),我们将重点放在C#WindowsForms上,因为用户上一次问题是在这个环境下。同时,我们也提供其他常见UI框架的示例。注意:引用[1]提到了用JavaRobot模拟鼠标操作,引用[2]是Vue3中获取鼠标坐标,引用[3]是PyQt5中pyqtgraph获取鼠标坐标,引用[4]是PowerShell获取鼠标坐标,引用[5]是Unity中获取鼠标点击位置并放置UI。由于用户要求“在UI中获取鼠标位置坐标”,我们将提供以下技术栈的完整代码示例:1.C#WindowsForms(基于用户上一次问题)2.WPF(C#)3.Vue3(JavaScript/TypeScript)4.PyQt5(Python)我们首先给出C#WindowsForms的完整示例,因为用户历史问题在此。方案一:C#WindowsForms在WindowsForms中,可以通过控件的鼠标事件(如MouseMove)来获取鼠标相对于控件或屏幕的坐标。步骤:1.创建一个WindowsForms项目。2.在窗体上添加一个控件(例如Panel)用于捕获鼠标事件。3.订阅该控件的MouseMove事件。4.在事件处理程序中获取鼠标坐标。完整代码示例:```csharpusingSystem;usingSystem.Drawing;usingSystem.Windows.Forms;namespaceMouseCoordinatesExample{publicpartialclassMainForm:Form{privateLabellblCoordinates;//用于显示坐标的标签publicMainForm(){InitializeComponent();InitializeUI();}privatevoidInitializeUI(){//创建一个Panel作为鼠标移动区域Panelpanel=newPanel{Dock=DockStyle.Fill,BackColor=Color.LightBlue};panel.MouseMove+=Panel_MouseMove;//创建标签用于显示坐标lblCoordinates=newLabel{Dock=DockStyle.Bottom,Height=30,TextAlign=ContentAlignment.MiddleCenter};Controls.Add(panel);Controls.Add(lblCoordinates);}privatevoidPanel_MouseMove(objectsender,MouseEventArgse){//相对于Panel的坐标PointrelativePoint=e.Location;//获取屏幕绝对坐标Controlpanel=senderasControl;PointscreenPoint=panel.PointToScreen(relativePoint);//显示坐标lblCoordinates.Text=$"相对坐标:({relativePoint.X},{relativePoint.Y})|屏幕坐标:({screenPoint.X},{screenPoint.Y})";}[STAThread]staticvoidMain(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(newMainForm());}}}```方案二:WPF(C#)在WPF中,我们可以通过Mouse.GetPosition方法获取鼠标相对于某个元素的坐标,以及使用PointToScreen方法获取屏幕坐标。完整代码示例:```xml<!--MainWindow.xaml--><Windowx:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MouseCoordinates"Height="350"Width="525"><GridMouseMove="Grid_MouseMove"><Labelx:Name="lblCoordinates"HorizontalAlignment="Left"VerticalAlignment="Top"Margin="10"/></Grid></Window>``````csharp//MainWindow.xaml.csusingSystem.Windows;usingSystem.Windows.Input;usingSystem.Windows.Controls;namespaceWpfApp{publicpartialclassMainWindow:Window{publicMainWindow(){InitializeComponent();}privatevoidGrid_MouseMove(objectsender,MouseEventArgse){Gridgrid=senderasGrid;//获取鼠标相对于Grid的位置PointrelativePoint=e.GetPosition(grid);//获取屏幕坐标PointscreenPoint=grid.PointToScreen(relativePoint);lblCoordinates.Content=$"相对坐标:({relativePoint.X:F0},{relativePoint.Y:F0})|屏幕坐标:({screenPoint.X:F0},{screenPoint.Y:F0})";}}}```方案三:Vue3(JavaScript/TypeScript)引用[2]提供了Vue3中获取鼠标坐标的方法,我们稍作修改以显示在页面上。完整代码示例:```vue<template><divid="app"@mousemove="updateMousePosition"><p>鼠标坐标:x:{{x}},y:{{y}}</p><divid="mouse-position"ref="positionElement"style="position:absolute;background-color:yellow;">x:{{x}},y:{{y}}</div></div></template><script>import{ref,onMounted,onBeforeUnmount}from'vue';exportdefault{setup(){constx=ref(0);consty=ref(0);constpositionElement=ref(null);functionupdateMousePosition(event){x.value=event.pageX;y.value=event.pageY;//更新显示元素位置(可选)if(positionElement.value){positionElement.value.style.left=event.pageX+20+'px';positionElement.value.style.top=event.pageY+20+'px';}}onMounted(()=>{document.addEventListener('mousemove',updateMousePosition);});onBeforeUnmount(()=>{document.removeEventListener('mousemove',updateMousePosition);});return{x,y,positionElement};}};</script><style>#app{width:100vw;height:100vh;position:relative;}</style>```方案四:PyQt5(Python)引用[3]提到在PyQt5中通过pyqtgraph获取鼠标坐标,我们这里使用PyQt5的标准控件。完整代码示例:```pythonimportsysfromPyQt5.QtWidgetsimportQApplication,QMainWindow,QLabelfromPyQt5.QtCoreimportQtclassMainWindow(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle("MouseCoordinates")self.setGeometry(100,100,800,600)#创建标签用于显示坐标self.label=QLabel(self)self.label.setAlignment(Qt.AlignCenter)self.label.setGeometry(0,0,400,30)self.label.move(10,10)#设置鼠标跟踪self.setMouseTracking(True)self.centralWidget().setMouseTracking(True)#如果设置中央部件则需要defmouseMoveEvent(self,event):#获取鼠标相对于窗口的位置relative_pos=event.pos()#获取屏幕坐标screen_pos=self.mapToGlobal(relative_pos)self.label.setText(f"相对坐标:({relative_pos.x()},{relative_pos.y()})|屏幕坐标:({screen_pos.x()},{screen_pos.y()})")if__name__=="__main__":app=QApplication(sys.argv)window=MainWindow()window.show()sys.exit(app.exec_())```注意:在PyQt5中,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值