pyqt5學習筆記——鼠標拖動代碼

以下代碼可以實現點擊窗口任意位置進行窗口拖動。

def mousePressEvent(self, e):
        if e.button() == Qt.LeftButton:
            self.m_drag = True
            self.m_DragPosition = e.globalPos() - self.pos()
            e.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))

    def mouseReleaseEvent(self, e):
        if e.button() == Qt.LeftButton:
            self.m_drag = False
            self.setCursor(QCursor(Qt.ArrowCursor))

    def mouseMoveEvent(self, e):
        if Qt.LeftButton and self.m_drag:
            self.move(e.globalPos() - self.m_DragPosition)
            e.accept()

mousePressEvent——鼠標點擊事件
mouseMoveEvent——鼠標移動事件
mouseReleaseEvent——鼠標釋放事件

這裏寫圖片描述

self.move(x,y)——是將當前控件移動的父控件的某個位置,x,y是父控件的座標。
(注意:是移動到父控件的(x,y)位置,不是以當前位置爲基準進行移動)

發佈了68 篇原創文章 · 獲贊 36 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章