PDA

View Full Version : Open PDF using Button Click



tndave
5th August 2018, 01:41
Good afternoon,

Have a little problem , I am trying to open a PDF from a sub-directory in my application folder when a button or menu item is clicked. I have tried a couple different things but neither seem to work. They are as follows:


void MainWindow::on_actionManual_triggered()
{
QDesktopServices::openUrl(QUrl::fromLocalFile(QDir ::currentPath() + "/docs/" + "nameof.pdf"()));

}

and


void MainWindow::on_actionManual_triggered()
{
//QDesktopServices::openUrl(QUrl("file:///docs/nameof.pdf"));

}

Neither work lol. I know I am probably missing something minor but can't put my finger on it.

Any suggestions?

Cobra91151
5th August 2018, 18:25
Hi! I think your file path is wrong. Try my solution:


QDesktopServices::openUrl(QUrl::fromLocalFile(qApp->applicationDirPath() + "/docs/" + "nameof.pdf"));

tndave
6th August 2018, 18:41
Hi! I think your file path is wrong. Try my solution:


QDesktopServices::openUrl(QUrl::fromLocalFile(qApp->applicationDirPath() + "/docs/" + "nameof.pdf"));

Cobra91151

that worked like a charm! Thank you very much for your assistance. Gonna save this info for future use lol.

d_stranz
6th August 2018, 20:23
Defensive programming tip: Always create a local QString variable to hold the result of expressions like


qApp->applicationDirPath() + "/docs/" + "nameof.pdf"

so that when things don't work as expected, you can look at the contents of the QString in the debugger or a QMessageBox in release mode and verify that the string actually contains the path you expect.

The environment that gets set up when you run in the debugger vs. running standalone from the command line (or an icon click from the desktop) often leads to unexpected values for paths. If you simply build a string and pass it directly into a method, you don't really have any good way of examining that string to figure out what's wrong.

tndave
7th August 2018, 04:22
Defensive programming tip: Always create a local QString variable to hold the result of expressions like


qApp->applicationDirPath() + "/docs/" + "nameof.pdf"

so that when things don't work as expected, you can look at the contents of the QString in the debugger or a QMessageBox in release mode and verify that the string actually contains the path you expect.

The environment that gets set up when you run in the debugger vs. running standalone from the command line (or an icon click from the desktop) often leads to unexpected values for paths. If you simply build a string and pass it directly into a method, you don't really have any good way of examining that string to figure out what's wrong.

Thank you very much for the tip d_stranz. Being somewhat new to C++ and QT any and all tips are welcome :)