Mytextedit.h:
1 #ifndef Mytextedit_h2 #defineMytextedit_h3 4#include <QTextEdit>5#include"ui_mytextedit.h"6#include <QUrl>7#include <QDropEvent>8#include <QMimeData>9#include <QString>Ten#include <QDragEnterEvent> One A classMytextedit: PublicQtextedit - { - Q_object the - Public: -Mytextedit (Qwidget *parent =0); -~Mytextedit (); + - //void Dragenterevent (Qdragenterevent *event); + voidDropevent (Qdropevent *Event); A at Private: - Ui::mytextedit Ui; - }; - - #endif //Mytextedit_h
Mytextedit.cpp:
1#include"mytextedit.h"2 3Mytextedit::mytextedit (Qwidget *parent)4 : Qtextedit (parent)5 {6UI.SETUPUI ( This);7 }8 9mytextedit::~Mytextedit ()Ten { One A } - - voidMytextedit::d ropevent (Qdropevent *Event) the { -qlist<qurl> URLs =Event->mimedata ()URLs (); - if(Urls.isempty ()) - { + return; - } + A //qurl url = urls.back (); at foreach(qurl URL, URLs) - { -QString file_name =url.tolocalfile (); - This-append (file_name); - } - } in - //void Mytextedit::d ragenterevent (qdragenterevent *event) to //{ + //if (Event->mimedata ()->hasformat ("Text/uri-list")) - //event->acceptproposedaction (); the //}
Above for the implementation of drag and drop files, display the file path of the custom class Mytextedit, found that the function void Mytextedit::d ragenterevent (qdragenterevent *event) commented out But the function has no effect,
When the Mytextedit text box class is removed and replaced with the Qwidget class, it is found that when an object is dragged onto the Qwidget form, dragenterevent () is called, and if the event calls Acceptproposedaction (), Indicates that you can drag and drop objects on this form.
By default, widgets are not accepted for dragging, so if you comment out the dragenterevent () function, the drag-and-drop function cannot be implemented on the Qwidget class, and QT automatically changes the cursor to indicate to the user that the widget is not a valid drop point. It is important to implement drag-and-drop on the Qwidget class,
You first need to set Setacceptdrops (true) to accept the drop event.
If you want to enable drag-and-drop on the graphics component, you can use the Setacceptdrops () method on the Qwidget to set the component to accept drag-and-drop actions, and when the drag-and-drop action occurs, there will be a corresponding qdragenterevent, qdragmoveevent, Events such as Qdragleaveevent and Qdropevent can redefine event handling such as Dragenterevent (), Dragmoveevent (), Dragleaveevent (), Dropevent (), To handle the corresponding drag-and-drop events, dragenterevent () and dropevent () are generally used.
QT Drag and drop function