Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 711
Luca Avatar asked Aug 05 '11 03:08

Luca


2 Answers

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.

like image 175
O.C. Avatar answered Oct 29 '22 07:10

O.C.


The above answer is informative but might be overwhelmed for this question. Connecting signals to QWebPage::action(OpenLinkInNewWindow) or overriding QWebPage::triggerAction should solve this problem.

like image 22
jichi Avatar answered Oct 29 '22 07:10

jichi