Skip to main content
 首页 » 编程设计

python之如何在 PyQt5 中用 QDrag 拖动时显示 QPushButton

2025年01月19日10unruledboy

当我拖动我的 QPushButton 时,它会消失直到掉落。我想在拖动时一直显示按钮。怎么做?

向下拖动我的 Button,包括 QDrag 对象。

如果需要,很乐意分享更多代码:)

我的屏幕照片

class DraggableCodeBlock(QPushButton): 
    def __init__(self, width, height, offset_left, offset_top, parent, command): 
 
        super().__init__(parent=parent) 
 
        self.parent = parent 
 
        self.setText(command) 
 
        self.show() 
 
    def mouseMoveEvent(self, e): 
 
        if e.buttons() != Qt.LeftButton: 
            return 
 
        mimeData = QMimeData() 
 
        drag = QDrag(self) 
        drag.setMimeData(mimeData) 
        drag.setHotSpot(e.pos() - self.rect().topLeft()) 
 
        dropAction = drag.exec_(Qt.MoveAction) 
        super(DraggableCodeBlock, self).mouseMoveEvent(e) 
 
    def mousePressEvent(self, e): 
 
        super().mousePressEvent(e) 
 
        if e.button() == Qt.LeftButton or not(self.is_mobile): 
            print('press') 

请您参考如下方法:

您必须通过setPixmap() 设置您想要显示的图像,要获取您应该使用grab() 的小部件的图像:

drag = QDrag(self) 
drag.setPixmap(self.grab())