在 QML 中拖放 [英] Drag and drop in QML

查看:15
本文介绍了在 QML 中拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 QML 中开发拖放功能?我想将一张图片拖放到另一张图片上.

How can I develop drag and drop functionality in QML? I want to drag and drop one image to another.

推荐答案

此时,您可能需要使用 C++,尤其是如果您想从 QML 应用程序外部接受 drop(例如,用户拖动文件从文件管理器到您的应用程序).下面是一个实现 DropArea 项的示例组件类:

At this point in time, you will probably need to use C++, especially if you want to accept drops from outside the QML application (e.g. the user drags a file from a file manager to your app). Here's an example component class to implement a DropArea item:

DropArea.h:

DropArea.h:

#ifndef DropArea_H
#define DropArea_H

#include <QDeclarativeItem>

/**
    An oversimplified prototype Item which accepts any drop that includes
    data with mime type of text/plain, and just emits the text.
*/
class DropArea : public QDeclarativeItem
{
    Q_OBJECT
    Q_PROPERTY(bool acceptingDrops READ isAcceptingDrops WRITE setAcceptingDrops NOTIFY acceptingDropsChanged)

public:
    DropArea(QDeclarativeItem *parent=0);
    bool isAcceptingDrops() const { return m_accepting; }
    void setAcceptingDrops(bool accepting);

signals:
    void textDrop(QString text);
    void acceptingDropsChanged();

protected:
    void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
    void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
    void dropEvent(QGraphicsSceneDragDropEvent *event);

private:
    bool m_accepting;
};

#endif

DropArea.cpp:

DropArea.cpp:

#include <QGraphicsSceneDragDropEvent>
#include <QMimeData>
#include "DropArea.h"

DropArea::DropArea(QDeclarativeItem *parent)
        : QDeclarativeItem(parent),
    m_accepting(true)
{
    setAcceptDrops(m_accepting);
}

void DropArea::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
    event->acceptProposedAction();
    setCursor(Qt::DragMoveCursor);
}

void DropArea::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
    unsetCursor();
}

void DropArea::dropEvent(QGraphicsSceneDragDropEvent *event)
{
    emit textDrop(event->mimeData()->text());
    unsetCursor();
}

void DropArea::setAcceptingDrops(bool accepting)
{
    if (accepting == m_accepting)
                return;

    m_accepting = accepting;
    setAcceptDrops(m_accepting);
    emit acceptingDropsChanged();
}

你的 QML:

DropArea {
    onTextDrop: ...
}

您可以类似地实现 DragSourceArea.

And you can implement a DragSourceArea similarly.

这篇关于在 QML 中拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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