macosqtpathqdirqurl

Open local HTML file from code in Qt on Mac OSx


Hello i am facing a small issue with Qt on the Mac OSX.

So in my program i am trying to open a local .html file located in the same path as the application.

Given that Qt is cross-platform , my attempt worked for both Windows and Ubuntu and i assumed that OSX should not have an issue since it is Unix based.

This is my attmpet

void MainWindow::openBrowser(bool)
{
    QString link = QDir::currentPath()+"/index.html"; // rename the file

    if(! QDesktopServices::openUrl(QUrl(link.trimmed())))
    {
        displayMessage("Access Error", "Unable to open a file");
    }
}

The OSX cannot find the same index.html file and I am not sure why. Is there a better way to concatenate the path?


Solution

  • On MacOS, QUrl works using FQ name (file://absolute_file.name) and this should be the portable syntax on all platforms. this can be invoked like this:

    if(! QDesktopServices::openUrl(QUrl("file:" + link.trimmed()))) // windows does not like :// 
        {
            qDebug() << "Access Error", "Unable to open a file";
        }
    

    Although not needed for local html files, Qt uses this entry in Info.plist for external URLs:

    <key>NSAppTransportSecurity</key>
    <!-- NOTE! For more information, see: https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33-->
    <dict>
            <key>NSAllowsArbitraryLoads</key>
            <true/>
    </dict>