How to drag file from OSX Finder to QT Gui



  • This is my first attempt to use creator for a project.

    I've managed to use Qt to recreate the functionality of a small C++ app that allows the user to choose one or more binary data files and decode them to text files suitable for importation into a spreadsheet. It's become apparent that my boss, the only user, wants to use the drag and drop to drag a file or files from Finder to the app's icon or opened app rather than drill down to the files from my app.

    I'd like to implement this so that either the folder or files can be dragged and dropped but this I'm new at Qt and am not sure how to proceed. In creator I've checked the 'Allow drops' property for central widget but don't know how to receive the drop (except they would probably be added to a list).

    I could use a little direction here ...


  • Qt Champions 2016

    Hi and welcome
    Disclaimer: only tried on windows. but Qt is cross platform so might just work :)
    MyWindow being a QMainWindow/other widget
    so you add

    protected:
    void dragEnterEvent(QDragEnterEvent *e);
    void dropEvent(QDropEvent *e):
    
    

    to the mainwinow.h file.
    Then implement following:

    MyWindow::MyWindow(QWidget *parent) <<< dont copy this as you will have constructor already
    {
       .... other stuff--
        setAcceptDrops(true); <<< insert this
    }
    
    void MyWindow::dragEnterEvent(QDragEnterEvent *e)
    {
        if (e->mimeData()->hasUrls()) {
            e->acceptProposedAction(); // say yes please
        }
    }
    
    void MyWindow::dropEvent(QDropEvent *e)
    {
        foreach (const QUrl &url, e->mimeData()->urls()) {
            const QString &fileName = url.toLocalFile();
            qDebug() << "Dropped file:" << fileName;
        }
    }
    

    all is in here
    http://doc.qt.io/qt-5.5/dnd.html


  • Lifetime Qt Champion

    Hi,

    To add to @mrjj, if you want to add support for the dock icon drop, take a look at QOpenFileEvent There's an example there. Follow the link, the example is not part of Qt 5.5's documentation but will be in 5.6


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.