SetRootPath doesn't set work as expected - python

I have used part of a code (PyQt5) from this post
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication
class Main(QTreeView):
def __init__(self):
QTreeView.__init__(self)
model = QFileSystemModel()
model.setRootPath('C:\\')
self.setModel(model)
self.doubleClicked.connect(self.test)
def test(self, signal):
file_path=self.model().filePath(signal)
print(file_path)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
And i have a problem with this line
model.setRootPath('C:\')
When i run the program it always shows drives like C: D: just not the content of C:\ or even if i type "C:\Users\" or a path that doesn't even exists, it always just shows, see attached image, What am i doing wrong?
Image of PyQt Program showing file manager
I am using:
Windows 10,
PyCharm,
Python 3.5,
PyQt5,
Thanks for your help.

You must indicate to the QTreeView what is your root item with setRootIndex():
from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication
class Main(QTreeView):
def __init__(self):
QTreeView.__init__(self)
model = QFileSystemModel()
self.setModel(model)
model.setRootPath(QDir.rootPath())
self.setRootIndex(model.index("C:"))
self.doubleClicked.connect(self.test)
def test(self, signal):
file_path=self.model().filePath(signal)
print(file_path)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())

Related

PyQt5 Define the slot in a separate module for QShortcut

Main interacts with a GUI defined by a separate module. Two alternative approaches are used in Main to define the slot for a QShortcut. The lambda method works (but seems cumbersome). The direct method works, only if the lambda method is executed first. If the line with the lambda method is commented out, then the direct method fails (with no error message). Why does the direct method alone fail?
'''
# p.py
import sys
from PyQt5 import QtWidgets as qtw
from Q import MainWindow
class MyActions():
def __init__(self, my_window):
self.my_window = my_window
self.my_window.run.activated.connect(lambda: self.rmssg1()) # had to use this as a work-around
self.my_window.run.activated.connect(self.rmssg2) # expected this to work
def rmssg1(self):
self.my_window.my_label1.setText('Ctrl+R pressed -> mssg 1')
def rmssg2(self):
self.my_window.my_label2.setText('Ctrl+R pressed -> mssg 2')
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
mw = MainWindow()
MyActions(mw)
mw.show()
sys.exit(app.exec())
'''
Here's the GUI in a separate module
'''
#q.py
import sys
from PyQt5 import QtWidgets as qtw
from PyQt5.QtGui import QKeySequence
class MainWindow(qtw.QMainWindow):
def __init__(self, parent=None):
super().__init__()
self.my_label1 = qtw.QLabel("Enter Ctrl+R", self)
self.my_label1.setGeometry(20,20,200,30)
self.my_label2 = qtw.QLabel("Enter Ctrl+R", self)
self.my_label2.setGeometry(20, 50, 200, 30)
#define shortcut
self.run = qtw.QShortcut(QKeySequence('Ctrl+R'), self)
'''
The problem is simple: When you do MyActions(mw) not assign a variable to the object so memory can be lost, the solution is:
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
mw = MainWindow()
foo = MyActions(mw)
mw.show()
sys.exit(app.exec())

Pdfjs print button does not work with PyQt5

Straight to issue, when pdf loads with pdfjs into pyqt5, seems print button does not work correctly, also the same for download button.
How could this bug be fixed?
The code:
import sys
from PyQt5 import QtCore, QtWidgets, QtGui, QtWebEngineWidgets
PDFJS = 'file:///pdfjs/web/viewer.html'
PDF = 'file:///file0.pdf'
class PdfReport(QtWebEngineWidgets.QWebEngineView):
def __init__(self, parent=None):
super(PdfReport, self).__init__(parent)
self.load(QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF)))
def sizeHint(self):
return QtCore.QSize(640, 480)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
im = PdfReport()
im.show()
sys.exit(app.exec_())
Display:
Any idea how to fix that?
The print task is not enabled in Qt WebEngine so the fault is displayed (I'm still trying to get the data). But in the case of the download button of the PDF it is possible and for this you must use the downloadRequested signal of the QWebEngineProfile:
import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PDFJS = QtCore.QUrl.fromLocalFile(
os.path.join(CURRENT_DIR, "pdfjs/web/viewer.html")
).toString()
class PdfReport(QtWebEngineWidgets.QWebEngineView):
def __init__(self, parent=None):
super(PdfReport, self).__init__(parent)
QtWebEngineWidgets.QWebEngineProfile.defaultProfile().downloadRequested.connect(
self.on_downloadRequested
)
def load_pdf(self, filename):
url = QtCore.QUrl.fromLocalFile(filename).toString()
self.load(QtCore.QUrl.fromUserInput("%s?file=%s" % (PDFJS, url)))
def sizeHint(self):
return QtCore.QSize(640, 480)
#QtCore.pyqtSlot(QtWebEngineWidgets.QWebEngineDownloadItem)
def on_downloadRequested(self, download):
path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, "Save File", "sample.pdf", "*.pdf"
)
if path:
download.setPath(path)
download.accept()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = PdfReport()
path = os.path.join(CURRENT_DIR, "file0.pdf")
w.load_pdf(path)
w.show()
sys.exit(app.exec_())
That's not a PyQt5 button, that is a button from your web view. It may not work because of your webView object or because the web part of your code lacks functionality for the button.

PyQt5 method not connected to button

This is my code for running PyQt, however the selectFile method is not called by the button. The UI code is converted from QtCreator. I've checked my objectName for the button is browseCSV
import sys
from readCSV import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
import form
from function2 import *
from function4 import *
from Function6 import *
class App(QtWidgets.QMainWindow, form.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self) # This is defined in design.py file automatically
self.browseCSV.clicked.connect(self.selectFile)
def selectFile(self):
print ("Hello")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = form.Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You're not actually using your App class. So you need to do this:
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = App()
window.show()
sys.exit(app.exec_()
PS: don't ever use self.__class__ in a super call. In some scenarios, it can cause an infinite regress. If you're using Python 3, you can just use super().__init__() to avoid repeating the class name.

SVG icons with PyQt on Windows and Linux

I have a PyQt user interface as follows
import sys
from PyQt4 import QtGui
class Example(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.setWindowTitle('Example')
self.setWindowIcon(QtGui.QIcon('note_add.svg'))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
It works fine on Linux but it doesn't work well on Windows, because the SVG icon doesn't appear. I have two questions:
What is the proper way to use SVG icons with PyQt on Windows?
Is there a way to change the color fill of an SVG icon on the fly? This should work fine on both operating systems.
I know this is a few years late. But, better late than never. :)
For me, Qt works best when I define a specific directory. So, I'd implement this as so:
import sys
import os
from PyQt4 import QtGui
class Example(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
### Newly added code ###
self.current_directory = os.path.dirname(__file__)
self.note_icon = os.path.join( self.current_directory, 'note_add.svg' )
### ### ### ###
self.setWindowTitle('Example')
self.setWindowIcon(QtGui.QIcon(self.note_icon))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

PYQT Adding extra menu items to an existing UI before it opens

Hi I have designed a basic GUI in QT and created a .py file from it.
When the window starts up I want to add another menu item. I have tried a few pieces of code I found on google but nothing seems to work. The code will need to go in the method addAdminMenu()
from PyQt4 import QtGui
import sys
from supplypy.core.windows.main_window import Ui_MainWindow
class SRM(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
self.MainWindow = QtGui.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.MainWindow)
self.MainWindow.show()
sys.exit(self.app.exec_())
def addAdminMenu(self):
pass
#####Add code here to create a Admin menu####
if __name__ == '__main__':
srm = SRM()
It should be as simple as accessing the menuBar() of the QMainWindow and adding an item, for example: (I removed the Ui_MainWindow lines just because I don't know what it's for -- a Windows requirement?)
from PyQt4 import QtGui
import sys
class SRM(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
self.MainWindow = QtGui.QMainWindow()
self.menubar = self.MainWindow.menuBar()
self.MainWindow.show()
self.addAdminMenu()
sys.exit(self.app.exec_())
def addAdminMenu(self):
self.menubar.addMenu('&Admin');
if __name__ == '__main__':
srm = SRM()

Categories

Resources