鼠标移动事件崩溃的解决方法:为什么我的mouseMoveEvent方法会崩溃?
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《鼠标移动事件崩溃的解决方法:为什么我的mouseMoveEvent方法会崩溃?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

mousemoveevent崩溃的解决方法
你在提供的代码中遇到的崩溃是由以下原因引起的:
在mousemoveevent方法中,你尝试访问mousex和mousey变量,但未确保它们已在mousepressevent方法中进行了初始化。这会导致访问未定义的变量,从而导致程序崩溃。
为了解决此问题,你可以添加一个判断到mousepressevent方法,检查mousex和mousey变量是否已赋值。如果没有赋值,则在mousemoveevent方法中忽略这些变量。
修改后的代码如下:
import sys
from PyQt5.Qt import *
class Mwindow(QWidget):
def __init__(self):
super().__init__()
self.resize(500, 500)
self.move(250, 150)
self.setup_Ui()
def setup_Ui(self):
self.btn = QPushButton(self)
self.btn.setText("点击我")
self.btn.move(230, 150)
def mousePressEvent(self, evt):
self.mousex = evt.globalX()
self.mousey = evt.globalY()
self.btn_x = self.btn.x()
self.btn_y = self.btn.y()
def mouseMoveEvent(self, evt2):
# 检查 mousex 和 mousey 是否已赋值
if hasattr(self, "mousex") and hasattr(self, "mousey"):
print(self.mousex, self.mousey)
def mouseReleaseEvent(self, evt3):
# print(self.mouse_x,self.mouse_y)
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Mwindow()
win.setMouseTracking(True)
win.show()
sys.exit(app.exec_())
本篇关于《鼠标移动事件崩溃的解决方法:为什么我的mouseMoveEvent方法会崩溃?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注米云公众号!
