qt 如何让鼠标按住widget后可以拖动
要实现让鼠标按住widget后可以拖动,你可以通过重写QWidget的mousePressEvent、mouseMoveEvent和mouseReleaseEvent方法来实现。下面是一个简单的示例代码:
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt, QPoint
class DraggableWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowFlags(Qt.FramelessWindowHint) # 隐藏窗口标题栏
self.draggable = True
self.offset = QPoint() # 偏移量
def mousePressEvent(self, event):
if self.draggable and event.button() == Qt.LeftButton:
self.offset = event.pos()
def mouseMoveEvent(self, event):
if self.draggable and event.buttons() & Qt.LeftButton:
self.move(self.mapToParent(event.pos() - self.offset))
def mouseReleaseEvent(self, event):
self.offset = QPoint()
if __name__ == '__main__':
app = QApplication([])
widget = DraggableWidget()
widget.resize(200, 200)
widget.show()
app.exec_()
在上面的代码中,我们创建了一个名为DraggableWidget的QWidget子类。通过设置窗口的setWindowFlags(Qt.FramelessWindowHint),我们隐藏了窗口的标题栏,以便实现自定义的拖动行为。
在mousePressEvent方法中,我们判断鼠标按下的是左键,并将当前鼠标的位置保存为偏移量。
在mouseMoveEvent方法中,我们判断鼠标左键是按下的状态,并根据偏移量来移动窗口的位置。
在mouseReleaseEvent方法中,我们将偏移量重置为空。
最后,在main函数中,我们创建了一个DraggableWidget实例,并显示出来。你可以尝试按住窗口并拖动来移动窗口的位置
原文地址: http://www.cveoy.top/t/topic/iZcq 著作权归作者所有。请勿转载和采集!