PyQt5:单击QLabel作为超链接打开.pdf

时间:2018-05-07 09:38:31

标签: python python-3.x pyqt pyqt5 qlabel

我一直试图创建一些东西,让我点击Qlabel(转换为超链接)并打开一个.pdf文件。

我从PYQT QLabel link to open folder on computer 获得了以下两个想法:

创意1

   <div class="panel-body">
        <div class="row">
          <table class="table">
            <tr *ngFor="let row of rows"> <!-- rows is newly created array of array-->
                <td *ngFor="let column of  row "> <!-- row array that has details about columns-->
                  <a href="#" class="btn btn-danger btn-lg" role="button">
                    <span class="glyphicon glyphicon-list-alt"></span>
                    <br/>Apps</a>
                </td>
            </tr>
          </table>
        </div>
      </div>

创意2

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

这些想法似乎都没有打开那个pdf文件。我看到创建了超链接,但是如果我点击它,它什么都不做。

1 个答案:

答案 0 :(得分:0)

必须对URL进行编码:

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

除了显示完整路径,以便管理此资源的任何人都可以找到它。

为此,您必须使用toEncoded(),如下所示:

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_())