PyQt - 添加拖拽放到小部件 [英] PyQt - Add drag & drop to widget

查看:80
本文介绍了PyQt - 添加拖拽放到小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承自 QWidget 的类:

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")

我想添加以下功能:当在小部件上放置一些东西(比如一个文件)时,我想调用droppedR().我该怎么做?

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 ?

推荐答案

我不确定它是否能准确地回答您想要的问题,但是我之前在使用 dragDrop 时遇到了一些问题,也许这个问题和答案我花了很长时间这里.

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()acceptProposedAction() 方法接受dragDrop 事件
  2. 重新实现 dragEnterEvent dragMoveEventdropEvent.
  3. 在这些方法中,您应该做您想做的.例如,在 dropEvent 方法中调用 dropR 方法.
  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.

这篇关于PyQt - 添加拖拽放到小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆