PyQt - Add drag & drop to widget

2019-08-04 04:25发布

问题:

I have a class that inherits from QWidget :

from PyQt5.QtWidgets import *


class Widget(QWidget):
    def __init__(self, layoutname: str, width: int, height: int ) -> None:
        """
        Constructor, pass 0 to width and/or height if you want them to be defaults given at runtime
        :param layoutname: Layout, a Layout object will be built according to the class name passed
        :param width: int,  width of the widget
        :param height: int, height of the widget
        """
        super(QWidget, self).__init__()

    if width != 0:
        self.setFixedWidth(width)

    if height != 0:
        self.setFixedHeight(height)

    layout = layoutname()
    self.setLayout(layout)


def addChild(self, child: object)-> None:
    """
    Adds child as a child to the widget
    :param child: Widget, the child you want to add to the current widget
    """
    self.layout().addWidget(child)

def droppedR(self):
    print("DROPPED")

I want to add the following feature: When something is dropped (let's say a file) on the widget, I want to call droppedR(). How can I do that ?

回答1:

I'm not sure if it answers you exactly what you want, but I had some problems before with dragDrop and maybe this question and answer that I spent a really long time can help you out here.

Summarizing, the main reasoning would be:

  1. Accept dragDrop events with accept() and acceptProposedAction() methods
  2. Re-implement the dragEnterEvent dragMoveEvent and dropEvent.
  3. Inside these methods you should do what you want. For example call your droppedR methods inside the dropEvent methods.

It's up to you the logic you want to apply in each of the events.