link to file in OS in python for QTableWidgetItem - python

I want to create a hyperlink of (file_path ) using python that will point to the file in operating system. I am able to get the path of the file. How can I create a hyperlink of this path and store in a variable. I want to display this in the QtWidgets as link where user can click and open the file stored in windows OS.
file_path = os.path.join(dir_path, FileName)
self.documents.setItem(0, 0, QtWidgets.QTableWidgetItem(file_path))

You can use QLabel with html content to create clickable link.
from PyQt5 import QtWidgets, QtCore
import os
if __name__ == "__main__":
app = QtWidgets.QApplication([])
path = os.environ["USERPROFILE"]
text = "click me"
label = QtWidgets.QLabel('{}'.format(path, text))
label.show()
label.linkActivated.connect(os.startfile)
app.exec()

Related

Pyqt5 pdf viewer doesn't display zoom buttons or zoom percentage

I'm learning how to use pyqt, I'm using Windows 10 and python 3.10 and i'm testing a code to open pdf files, this allows you to select the file and then opens it on a new window. It works almost correctly except that doesn't show zoom buttons, or zoom percentage.
This is the code:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
def main():
print(
f"PyQt5 version: {QtCore.PYQT_VERSION_STR}, Qt version: {QtCore.QT_VERSION_STR}"
)
app = QtWidgets.QApplication(sys.argv)
filename, _ = QtWidgets.QFileDialog.getOpenFileName(None, filter="PDF (*.pdf)")
if not filename:
print("please select the .pdf file")
sys.exit(0)
view = QtWebEngineWidgets.QWebEngineView()
settings = view.settings()
settings.setAttribute(QtWebEngineWidgets.QWebEngineSettings.PluginsEnabled, True)
url = QtCore.QUrl.fromLocalFile(filename)
view.load(url)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I was wondering if I need to pass an extra setting to display zoom buttons on pdf viewer. Anyone can help me? I highlighted where buttons/actions supposed to display in the image below.
That problem is because Qt version, if you test with the most recent version, PyQt6 you will see that works.
You need to install PyQt6:
pip install pyqt6
You also need to install webengine for pyqt6:
pip install PyQt6-WebEngine
And you need to change your code to this:
import sys
from PyQt6 import QtCore, QtWidgets, QtWebEngineWidgets
def main():
print(
f"PyQt6 version: {QtCore.PYQT_VERSION_STR}, Qt version: {QtCore.QT_VERSION_STR}"
)
app = QtWidgets.QApplication(sys.argv)
filename, _ = QtWidgets.QFileDialog.getOpenFileName(None, filter="PDF (*.pdf)")
if not filename:
print("please select the .pdf file")
sys.exit(0)
view = QtWebEngineWidgets.QWebEngineView()
settings = view.settings()
settings.setAttribute(view.settings().WebAttribute.PluginsEnabled, True)
url = QtCore.QUrl.fromLocalFile(filename)
view.load(url)
view.resize(640, 480)
view.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
And now should look like this:

How to choose multiple files from file dialog and open at the same time and access them

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog
from PyQt5 import QtCore
import sys
def dialog():
file , check = QFileDialog.getOpenFileName(None, "QFileDialog.getOpenFileName()",
"", "All Files (*);;Python Files (*.py);;Text Files (*.txt)")
if check:
print(file)
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(400,400,300,300)
win.setWindowTitle("CodersLegacy")
button = QPushButton(win)
button.setText("Press")
button.clicked.connect(dialog)
button.move(50,50)
win.show()
sys.exit(app.exec_())
Here is the code to select and open a single file when I press a button. However, how can this is changed to select multiple files and open at the same time. I tried for the syntax, unfortunately, I could not find one.
You have to use the QFileDialog::getOpenFileNames() method, also the second value of the tuple that returns is not a check but a string that indicates the filter used, if you want to verify then you have to use the size of the filenames:
filenames, _ = QFileDialog.getOpenFileNames(
None,
"QFileDialog.getOpenFileNames()",
"",
"All Files (*);;Python Files (*.py);;Text Files (*.txt)",
)
if filenames:
for filename in filenames:
print(filename)

Why python not show in path icon?

I wrote below code
import sys,time
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
sys.path.append(r"C:\Users\hpaalm\Desktop")
a=QPushButton()
a.setIcon(QIcon('1.png'))
a.show()
app.exec_()
when i run it in IDE, it show my icon, but when run it in CMD it not show icon. what is problem?
python C:\Users\hpaalm\Desktop\a.py
sys.path contains a list of paths where python imports the modules, this does not serve to import files, icons or similar resources. Instead it is best to create a function that binds the directory path with the filename and return the full path of the icon:
import os
import sys
from PyQt5 import QtGui, QtWidgets
ICON_DIR = r"C:\Users\hpaalm\Desktop"
def get_path_icon(filename):
return os.path.join(ICON_DIR, filename)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
a = QtWidgets.QPushButton()
a.setIcon(QtGui.QIcon(get_path_icon('1.png')))
a.show()
sys.exit(app.exec_())

Open a .pdf by clicking on QLabel made as Hyperlink

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(' Reference Link')
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.
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_())

PyQt : Editable QFileSystemModel in a QTreeView

I've got this on my file System :
- myFolder
- mySubFolder
Within the TreeView I expand the folder "myFolder".
Then I rename it as "myFolder_2".
And finaly I try to rename the folder "mySubFolder" as "mySubFolder_2".
"mySubFolder_2" in is no more considered as a folder but as unknown with a size of -1 bytes and I've got the message : QFileSystemWatcher: failed to add paths: myFolder.
Here is the my source code :
from PyQt4 import QtGui
import sys
app = QtGui.QApplication(sys.argv)
treeView = QtGui.QTreeView()
fileSystemModel = QtGui.QFileSystemModel(treeView)
fileSystemModel.setReadOnly(False)
treeView.setModel(fileSystemModel)
folder = "."
treeView.setRootIndex(fileSystemModel.setRootPath(folder))
treeView.show()
end = app.exec_()
Any help will be welcome.
You need to set the root path on the model before setting it on the treeview:
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
treeView = QtGui.QTreeView()
fileSystemModel = QtGui.QFileSystemModel(treeView)
fileSystemModel.setReadOnly(False)
root = fileSystemModel.setRootPath('.')
treeView.setModel(fileSystemModel)
treeView.setRootIndex(root)
treeView.show()
app.exec_()

Categories