
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方法会崩溃?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号