I'm trying to open a specific folder from my PyQt program. I know I could've used webbrowser module
like this
import webbrowser, os
path="C:/Users"
webbrowser.open(os.path.realpath(path))
or I could've used os.startfile module like this
import os
path = "C:/Users"
path = os.path.realpath(path)
os.startfile(path)
or subprocess which isn't recommended on Qt platform. so I wonder how could you do it on PyQt properly (maybe using QProcess?). I don't want to open file or folder dialog because I just want to open the folder without doing anything with it. also, I want to save time for a future update on a different OS than Windows, so I didn't have to change this part. is it possible?. many thanks
A Qt cross-platform solution is to use QDesktopServices::openUrl():
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
app = QtWidgets.QApplication(sys.argv)
path = "C:/Users"
fullpath = os.path.realpath(path)
if not QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(fullpath)):
print("failed")
I managed to use QProcess to open explorer on specific path without additional module (e.g webbrowser). I only need platform module to determine which platform the program is running, like this
self.path = os.path.abspath(os.path.dirname(sys.argv[0]))
self.pathOutput = os.path.join(self.path, "output")
def open_explorer(self):
self._process = QtCore.QProcess(self)
if platform.system() == "Windows":
self._process.start("explorer",[os.path.realpath(self.pathOutput)])
elif platform.system() == "Darwin":
self._process.start("open",[os.path.realpath(self.pathOutput)])
I wrote a GUI in pyqt5 where you can enter two paths (file paths, directory paths, ...). Now my problem is the following:
(1) when I run it with the Anaconda Prompt window, and enter any longer path then it does the word wrap how I want it (and afai can tell correctly):
in this case using setTextElideMode works as well.
(2) when I run it with the windows command prompt (C:\[...]\Desktop>C:\[...]\python\3.8.1.0.0\python-3.8.1.amd64\python.exe C:\[...]\Desktop\cmd_problems.py) it begins wrapping the text directly after "C:" by inserting the normal ellipsis "..." - I have to stretch the column (manually) until the whole path is visible to make it show more than that:
using setTextElideMode does nothing.
Does anyone know how to get the first behavior when running the code from the windows cmd line? (I need this because I use a batch script to launch the program similar to making an .exe file.)
Here is my code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtWidgets import QTableWidget, QVBoxLayout
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Very Important Window")
cen = QWidget()
self.layout = QVBoxLayout()
self.setCentralWidget(cen)
cen.setLayout(self.layout)
self.tbl = QTableWidget()
self.tbl.setRowCount(1)
self.tbl.setColumnCount(2)
self.tbl.setTextElideMode(Qt.ElideRight)
col_names = ["FROM", "TO"]
self.tbl.setHorizontalHeaderLabels(col_names)
self.layout.addWidget(self.tbl)
def main():
app = QApplication([])
win = MyWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
This question already has answers here:
No files visible in the QFileDialog window
(2 answers)
Closed 3 years ago.
Using a piece of example code from tutorialspoint, I am unable to open a file dialog using that code.
I am using Ubuntu MATE 16.04, python version 3.7.4, PyQt5 version 5.13.1 and the following piece of code
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class filedialogdemo(QWidget):
def __init__(self, parent=None):
super(filedialogdemo, self).__init__(parent)
layout = QVBoxLayout()
self.btn = QPushButton("QFileDialog static method demo")
self.btn.clicked.connect(self.getfile)
layout.addWidget(self.btn)
self.le = QLabel("Hello")
layout.addWidget(self.le)
self.contents = QTextEdit()
layout.addWidget(self.contents)
self.setLayout(layout)
self.setWindowTitle("File Dialog demo")
def getfile(self):
fname, _ = QFileDialog.getOpenFileName(self, 'Open file',
'', "Image files (*.jpg *.gif)")
print('The file name is...', fname)
self.le.setPixmap(QPixmap(fname))
def main():
app = QApplication(sys.argv)
ex = filedialogdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Yesterday I executed the code on a Windows computer without any trouble. And since I am not getting any error messages, just a None in return.. I cant really debug it.. at least I dont know how.. Any help is very much appreciated
To clarify what I get, here is a screen shot:
In words: my GUI is created and I can interact with it. Which means that when I press a button, the connected function is called (since it prints out what I ask). But no file dialog/explorer is opened, hence the return of the procedure is None. Thus nothing is printed after The file name is...
EDIT2: I reinstalled the PyQt5 package with pip3, to test if that made any difference. But sadly, no..
EDIT3: As #ekhumuro rightfully said, if you run this code in a simple console (e.g. not Pycharm), then it should it run fine. And it did.
After some more searching I came across the answer. This helped me, to add the follow option to the openFileDialog
fname, _ = QFileDialog.getOpenFileName(self, 'Open file',
'', '',
options=QFileDialog.DontUseNativeDialog)
This answer was found by #wagnerpeer on the following SO question
No files visible in the QFileDialog window
EDIT: #ekhumoro his comment below mine is very important and correct. This solution might only be needed when working from within an IDE
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_())
So if I go into QtDesigner and build a UI, it'll be saved as a .ui file. How can I make this as a python file or use this in python?
Another way to use .ui in your code is:
from PyQt4 import QtCore, QtGui, uic
class MyWidget(QtGui.QWidget)
...
#somewhere in constructor:
uic.loadUi('MyWidget.ui', self)
both approaches are good. Do not forget, that if you use Qt resource files (extremely useful) for icons and so on, you must compile it too:
pyrcc4.exe -o ui/images_rc.py ui/images/images.qrc
Note, when uic compiles interface, it adds 'import images_rc' at the end of .py file, so you must compile resources into the file with this name, or rename it in generated code.
Combining Max's answer and Shriramana Sharma's mailing list post, I built a small working example for loading a mywindow.ui file containing a QMainWindow (so just choose to create a Main Window in Qt Designer's File-New dialog).
This is the code that loads it:
import sys
from PyQt4 import QtGui, uic
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
uic.loadUi('mywindow.ui', self)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
You need to generate a python file from your ui file with the pyuic tool (site-packages\pyqt4\bin)
pyuic form1.ui > form1.py
with pyqt4
pyuic4.bat form1.ui > form1.py
Then you can import the form1 into your script.
I found this article very helpful.
http://talk.maemo.org/archive/index.php/t-43663.html
I'll briefly describe the actions to create and change .ui file to .py file, taken from that article.
Start Qt Designer from your start menu.
From "New Form" window, create "Main Window"
From "Display Widgets" towards the bottom of your "Widget Box Menu" on the left hand side
add a "Label Widget". (Click Drag and Drop)
Double click on the newly added Label Widget to change its name to "Hello World"
at this point you can use Control + R hotkey to see how it will look.
Add buttons or text or other widgets by drag and drop if you want.
Now save your form.. File->Save As-> "Hello World.ui" (Control + S will also bring up
the "Save As" option) Keep note of the directory where you saved your "Hello World" .ui
file. (I saved mine in (C:) for convenience)
The file is created and saved, now we will Generate the Python code from it using pyuic!
From your start menu open a command window.
Now "cd" into the directory where you saved your "Hello World.ui" For me i just had to
"cd\" and was at my "C:>" prompt, where my "Hello World.ui" was saved to.
When you get to the directory where your file is stored type the following.
pyuic4 -x helloworld.ui -o helloworld.py
Congratulations!! You now have a python Qt4 GUI application!!
Double click your helloworld.py file to run it. ( I use pyscripter and upon double click
it opens in pyscripter, then i "run" the file from there)
Hope this helps someone.
You can also use uic in PyQt5 with the following code.
from PyQt5 import uic, QtWidgets
import sys
class Ui(QtWidgets.QDialog):
def __init__(self):
super(Ui, self).__init__()
uic.loadUi('SomeUi.ui', self)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())
The cleaner way in my opinion is to first export to .py as aforementioned:
pyuic4 foo.ui > foo.py
And then use it inside your code (e.g main.py), like:
from foo import Ui_MyWindow
class MyWindow(QtGui.QDialog):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = Ui_MyWindow()
self.ui.setupUi(self)
# go on setting up your handlers like:
# self.ui.okButton.clicked.connect(function_name)
# etc...
def main():
app = QtGui.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
This way gives the ability to other people who don't use qt-designer to read the code, and also keeps your functionality code outside foo.py that could be overwritten by designer. You just reference ui through MyWindow class as seen above.
You can convert your .ui files to an executable python file using the below command..
pyuic4 -x form1.ui > form1.py
Now you can straightaway execute the python file as
python3(whatever version) form1.py
You can import this file and you can use it.
you can compile the ui files like this
pyuic4 -x helloworld.ui -o helloworld.py
In order to compile .ui files to .py files, I did:
python pyuic.py form1.ui > form1.py
Att.
in pyqt5 to convert from a ui file to .py file
pyuic5.exe youruifile.ui -o outputpyfile.py -x
(November 2020) This worked for me (UBUNTU 20.04):
pyuic5 /home/someuser/Documents/untitled.ui > /home/someuser/Documents/untitled.py
Using Anaconda3 (September 2018) and QT designer 5.9.5.
In QT designer, save your file as ui.
Open Anaconda prompt. Search for your file: cd C:.... (copy/paste the access path of your file).
Then write: pyuic5 -x helloworld.ui -o helloworld.py (helloworld = name of your file). Enter.
Launch Spyder. Open your file .py.