Search code examples
qtpdfwindowhyperlinkqwebview

QWebView doesn't open links in new window and not start external application for handling pdf


I am using a QWebView in this way:

QWebView *window = new QWebView();
window->setUrl(QString("my url"));
window->show();

And it works. I can see the html page I want. The problem is this. By default if I "right click" on a link the action "Open in new window" is shown but if I click on it, nothing happens. If I "left click" on the same link it works. So the problem is that no new windows are open by QWebView. Does anyone know why?

I have another problem. Some links are pdf file so I expect that QWebView ask me to download it or to run an application to open it. But nothing happens instead. I think the problem is related to the fact that no new windows are allowed to be opened by QWebView and not on the pdf.

Obviously I tested the page with a web browser and everything work well, so the problem is in some settings of QWebView.

Does anyone know how to make QWebView open new windows when required?

Notes:

  • all links are local resources.

  • The html links use this syntax (and they works):

 <a href="./something.htm" TARGET="_parent">Some link</a>
  • The link to pdfs use this syntax (nothing happens when I click):
<a href="./pdf/mydoc.pdf" TARGET="pdfwin">Some pdf</a>

Solution

  • Try to handle cicks by yourself. Here is an example that can guide you. I have not compiled it though .

        QWebView *window = new QWebView();
        window->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);//Handle link clicks by yourself
        window->page()->setContextMenuPolicy(Qt::NoContextMenu); //No context menu is allowed if you don't need it
        connect( window, SIGNAL( linkClicked( QUrl ) ),
                      this, SLOT( linkClickedSlot( QUrl ) ) );
    
        window->setUrl(QString("my url"));
        window->show();
    
        //This slot handles all clicks    
        void MyWindow::linkClickedSlot( QUrl url )
        {
            if (url.ishtml()//isHtml does not exist actually you need to write something like it by yourself
                 window->load (url);
            else//non html (pdf) pages will be opened with default application
                QDesktopServices::openUrl( url );
        }
    

    Note that if the HTML you are displaying may containing relative/internal links to other parts of itself, then you should use QWebPage::DelegateExternalLinks instead of QWebPage::DelegateAllLinks.