Skip to main content
 首页 » 编程设计

python之如何在不按住鼠标按钮的情况下执行拖放操作

2024年11月24日9zfyouxi

1。目的

我的目的是构建一个像这样的鼠标右键单击菜单:

当用户点击 Grab and move 时,按钮应该从 QScrollArea() 中消失,并快速移向鼠标。当它到达鼠标指针时,按钮应该淡出并且可以开始拖放操作。


2。最小的、可重现的例子

我得到了一些工作,但还不完美。请复制粘贴下面的代码并使用 Python 3.x(我使用 Python 3.7)和 PyQt5 运行它。

Note: To make the line pixmap = QPixmap("my_pixmap.png") work properly, let it refer to an existing png-image on your computer.

from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 
import sys 
 
class MyButton(QPushButton): 
    ''' 
    A special push button. 
    ''' 
    def __init__(self, *args, **kwargs): 
        super().__init__(*args, **kwargs) 
        self.setFixedWidth(300) 
        self.setFixedHeight(30) 
        self.setContextMenuPolicy(Qt.CustomContextMenu) 
        self.customContextMenuRequested.connect(self.showMenu) 
        return 
 
    def showMenu(self, pos): 
        ''' 
        Show this popup menu when the user clicks with the right mouse button. 
        ''' 
        menu = QMenu() 
        menuAction_01 = menu.addAction("action 01") 
        menuAction_02 = menu.addAction("action 02") 
        menuAction_03 = menu.addAction("action 03") 
        menuAction_04 = menu.addAction("action 04") 
        menuAction_grab = menu.addAction("grab") 
        action = menu.exec_(self.mapToGlobal(pos)) 
        if action == menuAction_01: 
            print("clicked on action 01") 
        elif action == menuAction_02: 
            print("clicked on action 02") 
        elif action == menuAction_03: 
            print("clicked on action 03") 
        elif action == menuAction_04: 
            print("clicked on action 04") 
        elif action == menuAction_grab: 
            print("clicked on grab") 
            # 1. Start animation 
            #      -> button moves to mouse pointer 
            self.animate() 
            # 2. After animation finishes (about 1 sec) 
            #      -> start drag operation 
            QTimer.singleShot(1000, self.start_drag) 
        return 
 
    def animate(self): 
        ''' 
        The button removes itself from the QScrollArea() and flies to the mouse cursor. 
        For more details, see the anser of @eyllanesc at 
        https://stackoverflow.com/questions/56216698/how-display-a-qpropertyanimation-on-top-of-the-qscrollarea  
        ''' 
        startpoint = self.window().mapFromGlobal(self.mapToGlobal(QPoint())) 
        endpoint = self.window().mapFromGlobal(QCursor.pos()) 
        self.setParent(self.window()) 
        anim = QPropertyAnimation( 
            self, 
            b"pos", 
            self, 
            duration=1000, 
            startValue=startpoint, 
            endValue=endpoint, 
            finished=self.hide, 
        ) 
        anim.start() 
        self.show() 
        return 
 
    def start_drag(self): 
        ''' 
        Start the drag operation. 
        ''' 
        drag = QDrag(self) 
        pixmap = QPixmap("my_pixmap.png") 
        pixmap = pixmap.scaledToWidth(100, Qt.SmoothTransformation) 
        drag.setPixmap(pixmap) 
        mimeData = QMimeData() 
        mimeData.setText("Foobar") 
        drag.setMimeData(mimeData) 
        dropAction = drag.exec(Qt.CopyAction | Qt.MoveAction) 
        return 
 
 
class CustomMainWindow(QMainWindow): 
    def __init__(self): 
        super().__init__() 
        self.setGeometry(100, 100, 600, 300) 
        self.setWindowTitle("ANIMATION TEST") 
 
        # OUTER FRAME 
        # ============ 
        self.frm = QFrame() 
        self.frm.setStyleSheet(""" 
            QFrame { 
                background: #d3d7cf; 
                border: none; 
            } 
        """) 
        self.lyt = QHBoxLayout() 
        self.frm.setLayout(self.lyt) 
        self.setCentralWidget(self.frm) 
 
        # BUTTON FRAME 
        # ============= 
        self.btn_frm = QFrame() 
        self.btn_frm.setStyleSheet(""" 
            QFrame { 
                background: #ffffff; 
                border: none; 
            } 
        """) 
        self.btn_frm.setFixedWidth(400) 
        self.btn_frm.setFixedHeight(200) 
        self.btn_lyt = QVBoxLayout() 
        self.btn_lyt.setAlignment(Qt.AlignTop) 
        self.btn_lyt.setSpacing(5) 
        self.btn_frm.setLayout(self.btn_lyt) 
 
        # SCROLL AREA 
        # ============ 
        self.scrollArea = QScrollArea() 
        self.scrollArea.setStyleSheet(""" 
            QScrollArea { 
                border-style: solid; 
                border-width: 1px; 
            } 
        """) 
        self.scrollArea.setWidget(self.btn_frm) 
        self.scrollArea.setWidgetResizable(True) 
        self.scrollArea.setFixedWidth(400) 
        self.scrollArea.setFixedHeight(150) 
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) 
        self.lyt.addWidget(self.scrollArea) 
 
        # ADD BUTTONS TO BTN_LAYOUT 
        # ========================== 
        self.btn_lyt.addWidget(MyButton("Foo")) 
        self.btn_lyt.addWidget(MyButton("Bar")) 
        self.btn_lyt.addWidget(MyButton("Baz")) 
        self.btn_lyt.addWidget(MyButton("Qux")) 
        self.show() 
 
        self.setAcceptDrops(True) 
        return 
 
    def dropEvent(self, event): 
        event.acceptProposedAction() 
        print("dropEvent at {0!s}".format(event)) 
        return 
 
    def dragLeaveEvent(self, event): 
        event.accept() 
        return 
 
    def dragEnterEvent(self, event): 
        event.acceptProposedAction() 
        return 
 
if __name__== '__main__': 
    app = QApplication(sys.argv) 
    QApplication.setStyle(QStyleFactory.create('Plastique')) 
    myGUI = CustomMainWindow() 
    sys.exit(app.exec_()) 

运行脚本,你会在QScrollArea()中看到一个带有几个按钮的小窗口:

第 1 步: 用鼠标右键单击其中一个按钮。您应该会看到一个弹出菜单。点击“抓取”。

第 2 步: 按钮移动到您的鼠标指针。不要移动鼠标指针。

第 3 步: 一旦您的鼠标指针位于按钮上(不要移动鼠标,等待按钮到达),单击并按住鼠标按钮。

第 4 步: 现在移动鼠标(同时按住鼠标按钮)。您应该处于拖放操作中,像素图锁定到您的鼠标!

好吧,它有效,但也有一些缺点。


3。问题

在动画结束时,飞行按钮位于鼠标指针下方。但是,如果您稍微移动鼠标指针,按钮就会消失,并且您会错过拖放操作。
换句话说,我现在得到的并不是很健壮。用户很容易错过拖放操作。

注意:显然我在这里描述的问题只出现在 Windows 上(而不是在 Linux 上)。但我必须让这个东西在 Windows 上运行...


4。潜在的解决方案

我相信下面的方法会更好,而且对用户来说仍然很直观:

一旦按钮到达鼠标指针下方(动画结束),按钮就会消失。 拖放 操作会自动开始,无需单击并按住鼠标按钮。当您移动鼠标指针时,拖动会继续,直到您单击某个地方。鼠标按下是 dropEvent()。

你知道如何实现吗?或者您可能有其他方法?


5。备注

我的问题实际上是这个问题的续集: How display a QPropertyAnimation() on top of the QScrollArea()?
感谢@eyllanesc 解决了这个问题^_^

请您参考如下方法:

1。解决方案

在提出解决方案之前,我想感谢@eyllanesc 先生对我的帮助。没有他的帮助,我现在不会有解决方案。

from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 
import sys, functools 
 
class MyButton(QPushButton): 
    ''' 
    A special push button. 
    ''' 
    def __init__(self, *args, **kwargs): 
        super().__init__(*args, **kwargs) 
        self.setFixedWidth(300) 
        self.setFixedHeight(30) 
        self.setContextMenuPolicy(Qt.CustomContextMenu) 
        self.customContextMenuRequested.connect(self.showMenu) 
        self.dragStartPosition = 0 
        self.set_style(False) 
        return 
 
    def set_style(self, blink): 
        if blink: 
            background = "#d3d7cf" 
        else: 
            background = "#2e3436" 
        self.setStyleSheet(f""" 
            QPushButton {{ 
                /* white on red */ 
                background-color:{background}; 
                color:#ffffff; 
                border-color:#888a85; 
                border-style:solid; 
                border-width:1px; 
                border-radius: 6px; 
                font-family:Courier; 
                font-size:10pt; 
                padding:2px 2px 2px 2px; 
            }} 
        """) 
        self.update() 
        return 
 
    def showMenu(self, pos): 
        ''' 
        Show this popup menu when the user clicks with the right mouse button. 
        ''' 
        menu = QMenu() 
        menuAction_01 = menu.addAction("action 01") 
        menuAction_02 = menu.addAction("action 02") 
        menuAction_03 = menu.addAction("action 03") 
        menuAction_04 = menu.addAction("action 04") 
        menuAction_grab = menu.addAction("grab") 
        action = menu.exec_(self.mapToGlobal(pos)) 
        if action == menuAction_01: 
            print("clicked on action 01") 
        elif action == menuAction_02: 
            print("clicked on action 02") 
        elif action == menuAction_03: 
            print("clicked on action 03") 
        elif action == menuAction_04: 
            print("clicked on action 04") 
        elif action == menuAction_grab: 
            print("clicked on grab") 
            # Start animation -> button moves to mouse pointer 
            self.animate() 
        return 
 
    def animate(self): 
        ''' 
        The button removes itself from the QScrollArea() and flies to the mouse cursor. 
        For more details, see the anser of @eyllanesc at 
        https://stackoverflow.com/questions/56216698/how-display-a-qpropertyanimation-on-top-of-the-qscrollarea 
        ''' 
        def start(): 
            startpoint = self.window().mapFromGlobal(self.mapToGlobal(QPoint())) 
            endpoint = self.window().mapFromGlobal(QCursor.pos() - QPoint(int(self.width()/2), int(self.height()/2))) 
            self.setParent(self.window()) 
            anim = QPropertyAnimation( 
                self, 
                b"pos", 
                self, 
                duration=500, 
                startValue=startpoint, 
                endValue=endpoint, 
                finished=blink, 
            ) 
            anim.start() 
            self.show() 
            return 
        def blink(): 
            # Flash the button to catch attention 
            self.setText("GRAB ME") 
            QTimer.singleShot(10, functools.partial(self.set_style, True)) 
            QTimer.singleShot(100, functools.partial(self.set_style, False)) 
            QTimer.singleShot(200, functools.partial(self.set_style, True)) 
            QTimer.singleShot(300, functools.partial(self.set_style, False)) 
            QTimer.singleShot(400, functools.partial(self.set_style, True)) 
            QTimer.singleShot(500, functools.partial(self.set_style, False)) 
            finish() 
            return 
        def finish(): 
            # After two seconds, hide the button 
            # (even if user did not grab it) 
            QTimer.singleShot(2000, self.hide) 
            return 
        start() 
        return 
 
    def start_drag(self): 
        ''' 
        Start the drag operation. 
        ''' 
        # 1. Start of drag-and-drop operation 
        #    => button must disappear 
        self.hide() 
 
        # 2. Initiate drag-and-drop 
        drag = QDrag(self) 
        pixmap = QPixmap("my_pixmap.png") 
        pixmap = pixmap.scaledToWidth(100, Qt.SmoothTransformation) 
        drag.setPixmap(pixmap) 
        mimeData = QMimeData() 
        mimeData.setText("Foobar") 
        drag.setMimeData(mimeData) 
        dropAction = drag.exec(Qt.CopyAction | Qt.MoveAction) 
        return 
 
    def mousePressEvent(self, event): 
        ''' 
        Left or Right mouseclick 
        ''' 
        def leftmouse(): 
            print("left mouse click") 
            self.dragStartPosition = event.pos() 
            return 
        def rightmouse(): 
            print("right mouse click") 
            return 
        if event.button() == Qt.LeftButton: 
            leftmouse() 
            return 
        if event.button() == Qt.RightButton: 
            rightmouse() 
            return 
        return 
 
    def mouseMoveEvent(self, event): 
        ''' 
        Mouse move event 
        ''' 
        event.accept() 
        if event.buttons() == Qt.NoButton: 
            return 
        if self.dragStartPosition is None: 
            return 
        if (event.pos() - self.dragStartPosition).manhattanLength() < QApplication.startDragDistance(): 
            return 
        self.start_drag() 
        return 
 
class CustomMainWindow(QMainWindow): 
    def __init__(self): 
        super().__init__() 
        self.setGeometry(100, 100, 600, 300) 
        self.setWindowTitle("ANIMATION & DRAG AND DROP") 
 
        # OUTER FRAME 
        # ============ 
        self.frm = QFrame() 
        self.frm.setStyleSheet(""" 
            QFrame { 
                background: #d3d7cf; 
                border: none; 
            } 
        """) 
        self.lyt = QHBoxLayout() 
        self.frm.setLayout(self.lyt) 
        self.setCentralWidget(self.frm) 
 
        # BUTTON FRAME 
        # ============= 
        self.btn_frm = QFrame() 
        self.btn_frm.setStyleSheet(""" 
            QFrame { 
                background: #ffffff; 
                border: none; 
            } 
        """) 
        self.btn_frm.setFixedWidth(400) 
        self.btn_frm.setFixedHeight(200) 
        self.btn_lyt = QVBoxLayout() 
        self.btn_lyt.setAlignment(Qt.AlignTop) 
        self.btn_lyt.setSpacing(5) 
        self.btn_frm.setLayout(self.btn_lyt) 
 
        # SCROLL AREA 
        # ============ 
        self.scrollArea = QScrollArea() 
        self.scrollArea.setStyleSheet(""" 
            QScrollArea { 
                border-style: solid; 
                border-width: 1px; 
            } 
        """) 
        self.scrollArea.setWidget(self.btn_frm) 
        self.scrollArea.setWidgetResizable(True) 
        self.scrollArea.setFixedWidth(400) 
        self.scrollArea.setFixedHeight(150) 
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) 
        self.lyt.addWidget(self.scrollArea) 
 
        # ADD BUTTONS TO BTN_LAYOUT 
        # ========================== 
        self.btn_lyt.addWidget(MyButton("Foo")) 
        self.btn_lyt.addWidget(MyButton("Bar")) 
        self.btn_lyt.addWidget(MyButton("Baz")) 
        self.btn_lyt.addWidget(MyButton("Qux")) 
        self.show() 
 
        self.setAcceptDrops(True) 
        return 
 
    def dropEvent(self, event): 
        event.acceptProposedAction() 
        print("dropEvent at {0!s}".format(event)) 
        return 
 
    def dragLeaveEvent(self, event): 
        event.accept() 
        return 
 
    def dragEnterEvent(self, event): 
        event.acceptProposedAction() 
        return 
 
if __name__== '__main__': 
    app = QApplication(sys.argv) 
    QApplication.setStyle(QStyleFactory.create('Plastique')) 
    myGUI = CustomMainWindow() 
    sys.exit(app.exec_()) 

这是我改变的:

  1. 我改进了动画。当您单击鼠标右键菜单中的“抓取”时,不是左上角而是按钮的中间会飞到您的鼠标指针。这一改进使得在动画结束后更容易捕获按钮。

  2. 在动画结束时,按钮会短暂闪烁以引起用户的注意。按钮上的文字变为“捕获我”。按钮的 self.hide() 函数在两秒钟内未被调用。因此用户有两秒钟的时间来启动拖放操作。

  3. 以通常的方式启动拖放操作:按住鼠标左键并移动鼠标指针。

  4. 如果用户在两秒钟内没有做任何事情,该按钮就会消失。否则,该按钮将无限期地停留在那里。


2。结果

它就像一个魅力。只需复制 .py 文件中的代码,然后使用 Python 3.x(我有 Python 3.7)和 PyQt5 运行它:


3。结语

我知道这个解决方案并不是我一开始的目标:在不按住鼠标按钮的情况下执行拖放操作。不过,我认为新方法更好,因为它更接近拖放的一般直觉。