Qt learning path (54): Custom drag and drop Data Objects

Source: Internet
Author: User

In the previous example, we used the drag-and-drop object QMimeData provided by the system to store drag-and-drop data. For example, we used QMimeData: setText () to create a Text object and QMimeData: urls () to create a URL object. However, if you want to use custom objects as drag-and-drop data, such as user-defined classes, QMimeData alone may not be that easy. To implement this operation, we can select one of the following three implementation methods: the first method does not need to inherit any classes, but there are some limitations: Drag and Drop will not happen, we must also convert custom data objects to QByteArray objects. If you want to support many types of drag-and-drop Data, you must use a QMimeData class for each type of data, this may cause a class explosion. If the data is large, this method may reduce the maintainability of the system. However, the last two implementations do not have these problems, or they can reduce these problems and give us full control. Let's take a look at an application and use QTableWidget for drag and drop operations. The drag and drop types include plain/text, plain/html, and plain/csv. If you use the first implementation method, our code will be as follows:

 
 
  1. void MyTableWidget::mouseMoveEvent(QMouseEvent *event)  
  2. {  
  3.     if (event->buttons() & Qt::LeftButton) {  
  4.         int distance = (event->pos() - startPos).manhattanLength();  
  5.         if (distance >= QApplication::startDragDistance())  
  6.             performDrag();  
  7.     }  
  8.     QTableWidget::mouseMoveEvent(event);  
  9. }  
  10.  
  11. void MyTableWidget::performDrag()  
  12. {  
  13.     QString plainText = selectionAsPlainText();  
  14.     if (plainText.isEmpty())  
  15.         return;  
  16.  
  17.     QMimeData *mimeData = new QMimeData;  
  18.     mimeData->setText(plainText);  
  19.     mimeData->setHtml(toHtml(plainText));  
  20.     mimeData->setData("text/csv", toCsv(plainText).toUtf8());  
  21.  
  22.     QDrag *drag = new QDrag(this);  
  23.     drag->setMimeData(mimeData);  
  24.     if (drag->exec(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction)  
  25.         deleteSelection();  
  26. }  
We should have easily understood this code: In the javasmdrag () function, we call setText () and setHTML () of QMimeData () the function stores plain/text and plain/html data, and uses setData () to store text/csv data as binary QByteArray.
 
 
  1. QString MyTableWidget::toCsv(const QString &plainText)  
  2. {  
  3.     QString result = plainText;  
  4.     result.replace("\\", "\\\\");  
  5.     result.replace("\"", "\\\"");  
  6.     result.replace("\t", "\", \"");  
  7.     result.replace("\n", "\"\n\"");  
  8.     result.prepend("\"");  
  9.     result.append("\"");  
  10.     return result;  
  11. }  
  12.  
  13. QString MyTableWidget::toHtml(const QString &plainText)  
  14. {  
  15.     QString result = Qt::escape(plainText);  
  16.     result.replace("\t", "<td>");  
  17.     result.replace("\n", "\n<tr><td>");  
  18.     result.prepend("<table>\n<tr><td>");  
  19.     result.append("\n</table>");  
  20.     return result;  
  21. }  
The toCsv () and toHtml () functions extract and convert the data into csv and html data. For example, the following data
Red   Green   BlueCyan  Yellow  Magenta
Convert to csv format:
"Red", "Green", "Blue""Cyan", "Yellow", "Magenta"
Convert to html Format: <table>
<Tr> <td> Red <td> Green <td> Blue
<Tr> <td> Cyan <td> Yellow <td> Magenta
</Table> In the placed function, we use the following as before:
 
 
  1. void MyTableWidget::dropEvent(QDropEvent *event)  
  2. {  
  3.     if (event->mimeData()->hasFormat("text/csv")) {  
  4.         QByteArray csvData = event->mimeData()->data("text/csv");  
  5.         QString csvText = QString::fromUtf8(csvData);  
  6.         // ...  
  7.         event->acceptProposedAction();  
  8.     } else if (event->mimeData()->hasFormat("text/plain")) {  
  9.         QString plainText = event->mimeData()->text();  
  10.         // ...  
  11.         event->acceptProposedAction();  
  12.     }  
  13. }  
Although we accept three data types, we only accept two types in this function. As for the html type, we hope that if you drag the QTableWidget data to an HTML editor, it will be automatically converted to html code, however, we do not plan to support dragging external html code to QTableWidget. To make this code work, we need to set setAcceptDrops (true) and setSelectionMode (ContiguousSelection) in the constructor ). Well, the above is the implementation of the first method we mentioned. The complete implementation code is not provided here. You can try it as needed. Next we will re-implement this requirement according to the second method.
 
 
  1. class TableMimeData : public QMimeData  
  2. {  
  3.     Q_OBJECT  
  4.  
  5. public:  
  6.     TableMimeData(const QTableWidget *tableWidget,  
  7.                   const QTableWidgetSelectionRange &range);  
  8.  
  9.     const QTableWidget *tableWidget() const { return myTableWidget; }  
  10.     QTableWidgetSelectionRange range() const { return myRange; }  
  11.     QStringList formats() const;  
  12.  
  13. protected:  
  14.     QVariant retrieveData(const QString &format,  
  15.                           QVariant::Type preferredType) const;  
  16.  
  17. private:  
  18.     static QString toHtml(const QString &plainText);  
  19.     static QString toCsv(const QString &plainText);  
  20.  
  21.     QString text(int row, int column) const;  
  22.     QString rangeAsPlainText() const;  
  23.  
  24.     const QTableWidget *myTableWidget;  
  25.     QTableWidgetSelectionRange myRange;  
  26.     QStringList myFormats;  
  27. };  
To avoid storing specific data, we store the table and the coordinate pointer of the selected region.
 
 
  1. TableMimeData::TableMimeData(const QTableWidget *tableWidget,  
  2.                              const QTableWidgetSelectionRange &range)  
  3. {  
  4.     myTableWidget = tableWidget;  
  5.     myRange = range;  
  6.     myFormats << "text/csv" << "text/html" << "text/plain";  
  7. }  
  8.  
  9. QStringList TableMimeData::formats() const 
  10. {  
  11.     return myFormats;  
In the constructor, We initialize private variables. The formats () function returns a list of data types supported by MIME data objects. This list is not sequential, but the best practice is to put the "most suitable" type first. For applications that support multiple types, the first suitable type of storage is sometimes used directly.
 
 
  1. QVariant TableMimeData::retrieveData(const QString &format,  
  2.                                      QVariant::Type preferredType) const 
  3. {  
  4.     if (format == "text/plain") {  
  5.         return rangeAsPlainText();  
  6.     } else if (format == "text/csv") {  
  7.         return toCsv(rangeAsPlainText());  
  8.     } else if (format == "text/html") {  
  9.         return toHtml(rangeAsPlainText());  
  10.     } else {  
  11.         return QMimeData::retrieveData(format, preferredType);  
  12.     }  
The retrieveData () function returns the given MIME type as QVariant. The value of the format parameter is usually one of the return values of the formats () function, but we cannot assume that it must be one of the values, because not all applications will pass the formats () function checks the MIME type. Some return functions, such as text (), html (), urls (), imageData (), colorData (), and data () are actually retrieveData () in QMimeData () function. The second parameter preferredType indicates the type of data we should store in QVariant. Here, we simply ignore it, and in the else statement, we assume that QMimeData will automatically convert it to the required type.
 
 
  1. void MyTableWidget::dropEvent(QDropEvent *event)  
  2. {  
  3.     const TableMimeData *tableData =  
  4.             qobject_cast<const TableMimeData *>(event->mimeData());  
  5.  
  6.     if (tableData) {  
  7.         const QTableWidget *otherTable = tableData->tableWidget();  
  8.         QTableWidgetSelectionRange otherRange = tableData->range();  
  9.         // ...  
  10.         event->acceptProposedAction();  
  11.     } else if (event->mimeData()->hasFormat("text/csv")) {  
  12.         QByteArray csvData = event->mimeData()->data("text/csv");  
  13.         QString csvText = QString::fromUtf8(csvData);  
  14.         // ...  
  15.         event->acceptProposedAction();  
  16.     } else if (event->mimeData()->hasFormat("text/plain")) {  
  17.         QString plainText = event->mimeData()->text();  
  18.         // ...  
  19.         event->acceptProposedAction();  
  20.     }  
  21.     QTableWidget::mouseMoveEvent(event);  
In the placed function, we need to select the data type according to our own definition. We use the qobject_cast macro to convert the data type. If the conversion succeeds, the data comes from the same application. Therefore, we directly set the QTableWidget data. If the conversion fails, we use the general processing method.

This article is from the "bean space" blog, please be sure to keep this source http://devbean.blog.51cto.com/448512/288742

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.