2

I have been trying to create something which lets me click on Qlabel (converted to hyperlink) and opens a .pdf file.

I got the two following ideas from PYQT QLabel link to open folder on computer:

Idea 1

self.text_label.setText('<a href=file:///"/Documents/To%20be%20Saved/hello.pdf"> Reference Link</a>')
self.text_label.setOpenExternalLinks(True)

Idea 2

self.text_label.setText("<a href={}>Reference Link</a>".format("/Documents/To%20be%20Saved/hello.pdf"))
self.text_label.setOpenExternalLinks(True)

None of the ideas seem to open that pdf file. I see the hyperlink created but if I click it, it does nothing.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Shaurya Garg
  • 105
  • 3
  • 11
  • The two lines of code in the example reference different label objects. Was that accidental when writing your question on SO or are you actually accessing the wrong label in one of your lines of code? – three_pineapples May 07 '18 at 11:08
  • Thank you for the edit. That is by accident. I will correct it asap. – Shaurya Garg May 07 '18 at 15:54
  • @eyllanesc Hi! it is C:\Users\Shaurya\Documents\To be saved\hello.pdf. But isn’t the path of not much relevance to this problem? – Shaurya Garg May 07 '18 at 21:44

1 Answers1

3

The URL must be encoded:

file:///C:/Users/Shaurya/Documents/To%20be%20saved/hello.pdf

In addition to showing the fullpath so that whoever manages this resource as a browser can find it.

To do this you must use toEncoded() as shown below:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QLabel()
    path = r"C:\Users\Shaurya\Documents\To be saved\hello.pdf"
    # or
    # path = QDir.home().filePath(r"Documents\To be saved\hello.pdf")
    # or
    # path = QDir(QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)).filePath(r"To be saved\hello.pdf")
    url = bytearray(QUrl.fromLocalFile(path).toEncoded()).decode() # file:///C:/Users/Shaurya/Documents/To%20be%20saved/hello.pdf
    text = "<a href={}>Reference Link> </a>".format(url)
    w.setText(text)
    w.setOpenExternalLinks(True)
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241