首页 > 解决方案 > Qt中按下按钮和拖动按钮的区别?

问题描述

根据拖放文档,我能够在我的 QToolButton 上实现拖动功能,但这会覆盖标准按钮单击行为,我无法检查按钮是否被按下或是否有通过拖动开始拖动的意图鼠。这是我的 QToolBar..

class toolbarButton(QToolButton):
    
    def __init__(self, parent = None, item = None):
        super(toolbarButton, self).__init__(parent)
        self.setIcon(...)
        self.setIconSize(QSize(40, 40))
        self.dragStartPosition = 0
        ...

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragStartPosition = event.pos()
    
    def mouseMoveEvent(self, event):
        if not (event.buttons() and Qt.LeftButton):
            return
        if (event.pos() - self.dragStartPosition).manhattanLength() < QApplication.startDragDistance():
            return
        
        drag = QDrag(self)
        mimeData = QMimeData()
        ...
        drag.setMimeData(mimeData)
        drag.exec(Qt.CopyAction)
        
    def sizeHint(self):
        return self.minimumSizeHint()
    
    def minimumSizeHint(self):
        return QSize(30, 30)

我最初的想法是在距离小于 startdragdistance 时添加发射,但这是不正确的,因为它会在我每次移动鼠标时触发。有没有办法在 PyQt5 中实现这一点?我在按钮按下时获得标准 QToolButton 行为,在按钮拖动时获得自定义行为?

标签: pythonpyqtpyqt5

解决方案


当您覆盖一个方法时,您正在删除默认行为,因此不会发生这种情况,那么您必须通过 super() 调用父方法:

def mousePressEvent(self, event):
    super().mousePressEvent(event)
    if event.button() == Qt.LeftButton:
        self.dragStartPosition = event.pos()

推荐阅读