拖放

拖放提供了用户可以在应用程序之间 (和应用程序内部),转移信息的简单可视化使用机制。拖放在功能方面,类似于剪贴板的剪切和粘贴机制。

本文档描述基本拖放机制,和提纲在自定义控件中启用它的方式。很多 Qt 控件 (譬如:项视图和图形视图框架,及 Qt Widgets 和 Qt Quick 的编辑控件),也支持拖放操作。有关项视图和图形视图的更多信息,见 将拖放用于项视图 and 图形视图框架 .

拖放类

这些类处理拖放和必要的 MIME (多用途 Internet 邮件扩展) 类型编码/解码。

QDrag 支持基于 MIME 的拖放数据传输
QDragEnterEvent 被发送给 Widget 的事件当拖放动作进入时
QDragLeaveEvent 被发送给 Widget 的事件当拖放动作离开时
QDragMoveEvent 发送的事件,在拖放动作进行期间
QDropEvent 被发送的事件当拖放操作完成时

配置

The QStyleHints 对象提供了与拖放操作相关的一些特性:

  • QStyleHints::startDragTime () 描述用户必须在对象上按下鼠标按钮的时间数 (以毫秒为单位),在开始拖拽前。
  • QStyleHints::startDragDistance () indicates how far the user has to move the mouse while holding down a mouse button before the movement will be interpreted as dragging.
  • QStyleHints::startDragVelocity () indicates how fast (in pixels/second) the user has to move the mouse to start a drag. A value of 0 means that there is no such limit.

These quantities provide sensible default values that are compliant with the underlying windowing system for you to use if you provide drag and drop support in your controls.

在 Qt Quick 中拖放

The rest of the document focuses mainly on how to implement drag and drop in C++. For using drag and drop inside a Qt Quick scene, please read the documentation for the Qt Quick Drag , DragEvent ,和 DropArea items, as well as the Qt Quick 拖放 范例。

拖拽

要开始拖拽,创建 QDrag object, and call its exec() function. In most applications, it is a good idea to begin a drag and drop operation only after a mouse button has been pressed and the cursor has been moved a certain distance. However, the simplest way to enable dragging from a widget is to reimplement the widget's mousePressEvent() and start a drag and drop operation:

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton
        && iconLabel->geometry().contains(event->pos())) {
        QDrag *drag = new QDrag(this);
        QMimeData *mimeData = new QMimeData;
        mimeData->setText(commentEdit->toPlainText());
        drag->setMimeData(mimeData);
        drag->setPixmap(iconPixmap);
        Qt::DropAction dropAction = drag->exec();
        ...
    }
}
					

Although the user may take some time to complete the dragging operation, as far as the application is concerned the exec() function is a blocking function that returns with one of several values . These indicate how the operation ended, and are described in more detail below.

注意,exec() 函数不会阻塞主事件循环。

For widgets that need to distinguish between mouse clicks and drags, it is useful to reimplement the widget's mousePressEvent() function to record to start position of the drag:

void DragWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        dragStartPosition = event->pos();
}
					

Later, in mouseMoveEvent() , we can determine whether a drag should begin, and construct a drag object to handle the operation:

void DragWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (!(event->buttons() & Qt::LeftButton))
        return;
    if ((event->pos() - dragStartPosition).manhattanLength()
         < QApplication::startDragDistance())
        return;
    QDrag *drag = new QDrag(this);
    QMimeData *mimeData = new QMimeData;
    mimeData->setData(mimeType, data);
    drag->setMimeData(mimeData);
    Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
    ...
}
					

This particular approach uses the QPoint::manhattanLength () function to get a rough estimate of the distance between where the mouse click occurred and the current cursor position. This function trades accuracy for speed, and is usually suitable for this purpose.

掉落

To be able to receive media dropped on a widget, call setAcceptDrops(true) for the widget, and reimplement the dragEnterEvent() and dropEvent() event handler functions.

For example, the following code enables drop events in the constructor of a QWidget subclass, making it possible to usefully implement drop event handlers:

Window::Window(QWidget *parent)
    : QWidget(parent)
{
    ...
    setAcceptDrops(true);
}
					

The dragEnterEvent() function is typically used to inform Qt about the types of data that the widget accepts. You must reimplement this function if you want to receive either QDragMoveEvent or QDropEvent in your reimplementations of dragMoveEvent() and dropEvent() .

The following code shows how dragEnterEvent() can be reimplemented to tell the drag and drop system that we can only handle plain text:

void Window::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasFormat("text/plain"))
        event->acceptProposedAction();
}
					

The dropEvent() is used to unpack dropped data and handle it in way that is suitable for your application.

In the following code, the text supplied in the event is passed to a QTextBrowser QComboBox is filled with the list of MIME types that are used to describe the data:

void Window::dropEvent(QDropEvent *event)
{
    textBrowser->setPlainText(event->mimeData()->text());
    mimeTypeCombo->clear();
    mimeTypeCombo->addItems(event->mimeData()->formats());
    event->acceptProposedAction();
}
					

In this case, we accept the proposed action without checking what it is. In a real world application, it may be necessary to return from the dropEvent() function without accepting the proposed action or handling the data if the action is not relevant. For example, we may choose to ignore Qt::LinkAction actions if we do not support links to external sources in our application.

覆写提议动作

We may also ignore the proposed action, and perform some other action on the data. To do this, we would call the event object's setDropAction() with the preferred action from Qt::DropAction before calling accept() . This ensures that the replacement drop action is used instead of the proposed action.

For more sophisticated applications, reimplementing dragMoveEvent() and dragLeaveEvent() will let you make certain parts of your widgets sensitive to drop events, and give you more control over drag and drop in your application.

子类化复杂 Widget

Certain standard Qt widgets provide their own support for drag and drop. When subclassing these widgets, it may be necessary to reimplement dragMoveEvent() in addition to dragEnterEvent() and dropEvent() to prevent the base class from providing default drag and drop handling, and to handle any special cases you are interested in.

拖放动作

In the simplest case, the target of a drag and drop action receives a copy of the data being dragged, and the source decides whether to delete the original. This is described by the CopyAction action. The target may also choose to handle other actions, specifically the MoveAction and LinkAction actions. If the source calls QDrag::exec (), and it returns MoveAction , the source is responsible for deleting any original data if it chooses to do so. The QMimeData and QDrag objects created by the source widget should not be deleted - they will be destroyed by Qt. The target is responsible for taking ownership of the data sent in the drag and drop operation; this is usually done by keeping references to the data.

If the target understands the LinkAction action, it should store its own reference to the original information; the source does not need to perform any further processing on the data. The most common use of drag and drop actions is when performing a Move within the same widget; see the section on 掉落动作 for more information about this feature.

The other major use of drag actions is when using a reference type such as text/uri-list, where the dragged data are actually references to files or objects.

添加新的拖放类型

Drag and drop is not limited to text and images. Any type of information can be transferred in a drag and drop operation. To drag information between applications, the applications must be able to indicate to each other which data formats they can accept and which they can produce. This is achieved using MIME 类型 QDrag object constructed by the source contains a list of MIME types that it uses to represent the data (ordered from most appropriate to least appropriate), and the drop target uses one of these to access the data. For common data types, the convenience functions handle the MIME types used transparently but, for custom data types, it is necessary to state them explicitly.

To implement drag and drop actions for a type of information that is not covered by the QDrag convenience functions, the first and most important step is to look for existing formats that are appropriate: The Internet Assigned Numbers Authority ( IANA ) 提供 MIME 媒体类型的分层列表 at the Information Sciences Institute ( ISI ). Using standard MIME types maximizes the interoperability of your application with other software now and in the future.

To support an additional media type, simply set the data in the QMimeData 对象采用 setData() function, supplying the full MIME type and a QByteArray containing the data in the appropriate format. The following code takes a pixmap from a label and stores it as a Portable Network Graphics (PNG) file in a QMimeData 对象:

    QByteArray output;
    QBuffer outputBuffer(&output);
    outputBuffer.open(QIODevice::WriteOnly);
    imageLabel->pixmap()->toImage().save(&outputBuffer, "PNG");
    mimeData->setData("image/png", output);
					

Of course, for this case we could have simply used setImageData() instead to supply image data in a variety of formats:

    mimeData->setImageData(QVariant(*imageLabel->pixmap()));
					

The QByteArray approach is still useful in this case because it provides greater control over the amount of data stored in the QMimeData 对象。

Note that custom datatypes used in item views must be declared as 元对象 and that stream operators for them must be implemented.

掉落动作

在剪贴板模型中,用户可以 cut or copy the source information, then later paste it. Similarly in the drag and drop model, the user can drag a copy of the information or they can drag the information itself to a new place ( moving it). The drag and drop model has an additional complication for the programmer: The program doesn't know whether the user wants to cut or copy the information until the operation is complete. This often makes no difference when dragging information between applications, but within an application it is important to check which drop action was used.

We can reimplement the mouseMoveEvent() for a widget, and start a drag and drop operation with a combination of possible drop actions. For example, we may want to ensure that dragging always moves objects in the widget:

void DragWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (!(event->buttons() & Qt::LeftButton))
        return;
    if ((event->pos() - dragStartPosition).manhattanLength()
         < QApplication::startDragDistance())
        return;
    QDrag *drag = new QDrag(this);
    QMimeData *mimeData = new QMimeData;
    mimeData->setData(mimeType, data);
    drag->setMimeData(mimeData);
    Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
    ...
}
					

The action returned by the exec() function may default to a CopyAction if the information is dropped into another application but, if it is dropped in another widget in the same application, we may obtain a different drop action.

The proposed drop actions can be filtered in a widget's dragMoveEvent() function. However, it is possible to accept all proposed actions in the dragEnterEvent() and let the user decide which they want to accept later:

void DragWidget::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}
					

When a drop occurs in the widget, the dropEvent() handler function is called, and we can deal with each possible action in turn. First, we deal with drag and drop operations within the same widget:

void DragWidget::dropEvent(QDropEvent *event)
{
    if (event->source() == this && event->possibleActions() & Qt::MoveAction)
        return;
					

In this case, we refuse to deal with move operations. Each type of drop action that we accept is checked and dealt with accordingly:

    if (event->proposedAction() == Qt::MoveAction) {
        event->acceptProposedAction();
        // Process the data from the event.
    } else if (event->proposedAction() == Qt::CopyAction) {
        event->acceptProposedAction();
        // Process the data from the event.
    } else {
        // Ignore the drop.
        return;
    }
    ...
}
					

Note that we checked for individual drop actions in the above code. As mentioned above in the section on 覆写提议动作 , it is sometimes necessary to override the proposed drop action and choose a different one from the selection of possible drop actions. To do this, you need to check for the presence of each action in the value supplied by the event's possibleActions() , set the drop action with setDropAction() ,和调用 accept() .

掉落矩形

The widget's dragMoveEvent() can be used to restrict drops to certain parts of the widget by only accepting the proposed drop actions when the cursor is within those areas. For example, the following code accepts any proposed drop actions when the cursor is over a child widget ( dropFrame ):

void Window::dragMoveEvent(QDragMoveEvent *event)
{
    if (event->mimeData()->hasFormat("text/plain")
        && event->answerRect().intersects(dropFrame->geometry()))
        event->acceptProposedAction();
}
					

The dragMoveEvent() can also be used if you need to give visual feedback during a drag and drop operation, to scroll the window, or whatever is appropriate.

剪贴板

Applications can also communicate with each other by putting data on the clipboard. To access this, you need to obtain a QClipboard 对象从 QApplication 对象。

The QMimeData class is used to represent data that is transferred to and from the clipboard. To put data on the clipboard, you can use the setText(), setImage(), and setPixmap() convenience functions for common data types. These functions are similar to those found in the QMimeData class, except that they also take an additional argument that controls where the data is stored: If Clipboard is specified, the data is placed on the clipboard; if Selection is specified, the data is placed in the mouse selection (on X11 only). By default, data is put on the clipboard.

For example, we can copy the contents of a QLineEdit to the clipboard with the following code:

    QGuiApplication::clipboard()->setText(lineEdit->text(), QClipboard::Clipboard);
					

Data with different MIME types can also be put on the clipboard. Construct a QMimeData object and set data with setData() function in the way described in the previous section; this object can then be put on the clipboard with the setMimeData() 函数。

The QClipboard class can notify the application about changes to the data it contains via its dataChanged() signal. For example, we can monitor the clipboard by connecting this signal to a slot in a widget:

    connect(clipboard, SIGNAL(dataChanged()), this, SLOT(updateClipboard()));
					

The slot connected to this signal can read the data on the clipboard using one of the MIME types that can be used to represent it:

void ClipWindow::updateClipboard()
{
    QStringList formats = clipboard->mimeData()->formats();
    QByteArray data = clipboard->mimeData()->data(format);
    ...
}
					

The selectionChanged() 信号可以用于 X11 以监视鼠标选定。

范例

与其它应用程序进行互操作

在 X11,公共 XDND 协议 is used, while on Windows Qt uses the OLE standard, and Qt for macOS uses the Cocoa Drag Manager. On X11, XDND uses MIME, so no translation is necessary. The Qt API is the same regardless of the platform. On Windows, MIME-aware applications can communicate by using clipboard format names that are MIME types. Already some Windows applications use MIME naming conventions for their clipboard formats.

Custom classes for translating proprietary clipboard formats can be registered by reimplementing QWinMime on Windows or QMacPasteboardMime on macOS .