How to handle downloads in QWebEngine?

I know that QWebEngineProfile and QWebEngineDownloadItem are used in order to download something. But I don't understand how. I'm trying to use connects in order to achieve downloads. Here's my code

void MainWindow::handleDownloadSlot(QWebEngineDownloadItem *download) {
    download->accept();
}
void MainWindow::downloadRequested(QWebEngineDownloadItem *download) {
    download->accept();
}
  connect (pro,SIGNAL(downloadRequested(QWebEngineDownloadItem *)),this,SLOT(handleDownloadSlot(QWebEngineDownloadItem *)));

Upvotes: 0

Views: 3926

Answers (1)

mohabouje
mohabouje

Reputation: 4050

Check the Web Demo Browser example which includes an example with a Download Manager.

If you are sharing a default QWebEngineProfile, try:

    connect(QWebEngineProfile::defaultProfile(), SIGNAL(downloadRequested(QWebEngineDownloadItem*)),
                this, SLOT(downloadRequested(QWebEngineDownloadItem*)));

For a profile defined in a custom QWebEnginePage, try:

    connect(webView->page()->profile(), SIGNAL(downloadRequested(QWebEngineDownloadItem*)),
                this, SLOT(downloadRequested(QWebEngineDownloadItem*)));

Now handle your download to start:

void MainWindow::downloadRequested(QWebEngineDownloadItem* download) {
        if (download->savePageFormat() != QWebEngineDownloadItem::UnknownSaveFormat)  {
            qDebug() << "Format: " <<  download->savePageFormat();
            qDebug() << "Path: " << download->path();
            // If you want to modify something like the default path or the format
            download->setSavePageFormat(...);
            download->setPath(...);
            // Check your url to accept/reject the download
            download->accept();
        }
}

If you want to show a progress dialog with the download progress, just use signals availables in the class QWebEngineDownloadItem:

connect(download, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(setCurrentProgress(qint64, qint64)));

Upvotes: 2

Related Questions