1. 程式人生 > 程式設計 >python Qt5實現窗體跟蹤滑鼠移動

python Qt5實現窗體跟蹤滑鼠移動

我就廢話不多說了, 直接上程式碼吧!

from PyQt5.Qt import *
import sys
 
 
class Window(QWidget):
  def __init__(self):
    super().__init__()
    self.Flag=False
    self.setWindowTitle("視窗移動學習")
    self.resize(500,500)
    self.setup_ui()
 
  def setup_ui(self):
    pass
 
  def mousePressEvent(self,evt):
    #確定兩個點(滑鼠第一次按下的點)
    if evt.button()==Qt.LeftButton:#判斷是否為左鍵執行
      self.Flag=True
      self.mouse_x=evt.globalX()
      self.mouse_y=evt.globalY()
 
      self.origin_x=self.x()
      self.origin_y=self.y()
 
  def mouseMoveEvent(self,evt):
    if self.Flag==True:
      move_x=evt.globalX()-self.mouse_x
      move_y=evt.globalY()-self.mouse_y
      dest_x=self.origin_x+move_x
      dest_y=self.origin_y+move_y
      self.move(dest_x,dest_y)
  def mouseReleaseEvent(self,QMouseEvent):
    self.Flag=False
 
if __name__=='__main__':
  import sys
  app=QApplication(sys.argv)\
 
  window=Window()
  window.show()
  window.setMouseTracking(True)#滑鼠跟蹤
  sys.exit(app.exec_())

以上這篇python Qt5實現窗體跟蹤滑鼠移動就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。