PyQt5 | How to open a folder with a file preselected? - python

Currently I can open a folder by using
dirPath = os.path.dirname(os.path.abspath(self.oVidPath))
QDesktopServices.openUrl(QUrl.fromLocalFile(dirPath))
I want to know if there is anyway I can open folder with a file preselected?
I am okay if it only works on linux systems (nautilus is preferred)
edit : This application is only going be for linux systems

For windows
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.Qt import QProcess
if __name__ == '__main__':
app = QApplication(sys.argv)
command = "explorer /e, /select, c:\\windows\\regedit.exe"
process = QProcess()
process.start(command)
sys.exit(app.exec_())
For Linux
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.Qt import QProcess
if __name__ == '__main__':
app = QApplication(sys.argv)
command = "nautilus /var/log/dpkg.log"
process = QProcess()
process.start(command)
sys.exit(app.exec_())
FYI https://askubuntu.com/a/82717/249546

Related

execute ping command with GUI

While writing a GUI application in PyQt5 I encounter weird(for me) behavior.
When I wanted to open an information window and start doing another thing after it fully loads. I noticed that the information window does not load fully until the next block of code is done.
This is how it looks
Code that reproduces this unwanted behavior
from PyQt5.QtWidgets import QApplication,QMessageBox
import sys
import os
app = QApplication(sys.argv)
box = QMessageBox()
box.setText("Text")
box.show()
os.system("ping 8.8.8.8 ")
sys.exit(app.exec())
Behavior is the same whether I use QMessegBox, inherit it in another class or write my own QMeesgeBox type class.
I guess this behavior works like this because of os.system() function and I would use Process or Thread to make a workaround, but if It is possible I would like to ensure that window is fully loaded and then the next procedure is taking place.
Python version 3.7.0
PyQt5 version 5.12.1
Although the solutions of S.Nick and Guimoute seems to work but the reality is that it has only made the window show a moment but if you want to interact with it you will see that it is frozen, for example try to move the window to check it. The os.system() task is blocking so it must be executed in another thread
import os
import sys
from PyQt5.QtWidgets import QApplication,QMessageBox
import threading
app = QApplication(sys.argv)
box = QMessageBox()
box.setText("Text")
box.show()
def task():
os.system("ping 8.8.8.8 ")
threading.Thread(target=task, daemon=True).start()
# or threading.Thread(target=os.system, args=("ping 8.8.8.8 ",), daemon=True).start()
sys.exit(app.exec_())
Or use QProcess:
import sys
import os
from PyQt5.QtWidgets import QApplication,QMessageBox
from PyQt5.QtCore import QProcess
app = QApplication(sys.argv)
box = QMessageBox()
box.setText("Text")
box.show()
def on_readyReadStandardOutput():
print(process.readAllStandardOutput().data().decode(), end="")
process = QProcess()
process.start("ping", ["8.8.8.8"])
process.readyReadStandardOutput.connect(on_readyReadStandardOutput)
sys.exit(app.exec_())
Update
import os
import sys
from PyQt5 import QtCore, QtWidgets
class PingObject(QtCore.QObject):
finished = QtCore.pyqtSignal()
#QtCore.pyqtSlot()
def start(self):
os.system("ping 8.8.8.8")
self.finished.emit()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
box = QtWidgets.QMessageBox()
box.setText("Text")
box.show()
thread = QtCore.QThread()
thread.start()
ping = PingObject()
ping.moveToThread(thread)
QtCore.QTimer.singleShot(0, ping.start)
loop = QtCore.QEventLoop()
ping.finished.connect(loop.quit)
loop.exec_()
print("finished ping")
sys.exit(app.exec_())
Another Option:
import os
import sys
from PyQt5 import QtCore, QtWidgets
class Thread(QtCore.QThread):
def run(self):
response = os.popen("ping 8.8.8.8")
for line in response.readlines():
print(line)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
box = QtWidgets.QMessageBox()
box.setText("Text")
box.show()
thread = Thread()
thread.start()
ret = app.exec_()
thread.quit()
thread.wait()
sys.exit(ret)
Here is a single-line solution:
from PyQt5.QtWidgets import QApplication,QMessageBox
import sys
import os
app = QApplication(sys.argv)
box = QMessageBox()
box.setText("Text")
box.show()
QApplication.processEvents() # <------------ this one
os.system("ping 8.8.8.8 ")
sys.exit(app.exec())
As an option. Try it:
import sys
import os
from PyQt5.QtWidgets import QApplication,QMessageBox
from PyQt5.QtCore import QTimer
app = QApplication(sys.argv)
box = QMessageBox()
box.setText("Text")
box.show()
def osSystem():
os.system("ping 8.8.8.8 ")
QTimer.singleShot(20, osSystem )
#os.system("ping 8.8.8.8 ")
sys.exit(app.exec())

PySide2 not closing correctly with basic example

When I run the basic script:
import sys
from PySide2.QtWidgets import QApplication, QLabel
app = QApplication(sys.argv)
label = QLabel("Hello World")
label.show()
app.exec_()
forthe first time it all works fine. However, if I run it a second time I get:
File "../script.py", line 17, in <module>
app = QApplication(sys.argv)
RuntimeError: Please destroy the QApplication singleton before creating a new QApplication instance.
I am running the scripts in an Ubuntu machine. I get the same error in python2 and python3.
Thanks !
Probably your IDE has already created a QApplication, so the solution is to create a QApplication if it does not exist:
app = QApplication.instance()
if app is None:
app = QApplication(sys.argv)

PyQt5 Changing native dialog save text?

Is it possible to change the Save/Open/Cancel text of native file dialogs called by Qt, e.g.
from PyQt5.Qt import *
import sys
app = QApplication(sys.argv)
OpenFile = QFileDialog()
OpenFile.getExistingDirectory()
I've tried following some examples in C++, e.g. this, but it doesn't seem to have any effect. Maybe I'm doing something wrong?
Try it:
from PyQt5.Qt import *
import sys
app = QApplication(sys.argv)
OpenFile = QFileDialog()
#OpenFile.getExistingDirectory()
OpenFile.setFileMode(QFileDialog.DirectoryOnly)
OpenFile.setLabelText(QFileDialog.Accept, "+Accept+")
OpenFile.setLabelText(QFileDialog.Reject, "-REJECT-")
OpenFile.show()
sys.exit(app.exec_())

PyQt5 - how to bring the Qfiledialog to the front?

My code uses PyQt to open up a folder select dialog. Once a folder is selected it is minimized. I'd like for the dialog to pop up in front of any other windows. I haven't been able to find a solution yet. Any suggestions?
from sys import executable, argv
from subprocess import check_output
from PyQt5.QtWidgets import QFileDialog, QApplication
def gui_fname(directory=''):
file = check_output([executable, __file__, directory])
return file.strip()
if __name__ == "__main__":
directory = argv[1]
app = QApplication([directory])
folderpath = QFileDialog.getExistingDirectory(None, "Select folder")
I think your problem comes from the "None" in the following function.
folderpath = QFileDialog.getExistingDirectory(None, "Select folder")
The dialog modality cannot be set because it has no parent. Usually, instead of None we have self.
EDIT: Of cource app is not inheriting from QWidget. Sorry about that.
use this instead. I tested it an it work:
import sys
from subprocess import check_output
from PyQt5.QtWidgets import QFileDialog, QApplication, QWidget
def gui_fname(directory=''):
file = check_output([executable, __file__, directory])
return file.strip()
if __name__ == "__main__":
app = QApplication(sys.argv)
wid = QWidget()
folderpath = QFileDialog.getExistingDirectory(wid, "Select folder")
sys.exit(app.exec_())

Error on trying to convert a python file into an executable with cx_freeze

I've got code with PyQt:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
def main():
page = raw_input('Escriu una web: ')
app = QApplication(sys.argv)
view = QWebView()
view.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
view.load(QUrl(page))
view.setWindowTitle('Titanicus 0.1')
view.show()
app.exec_()
if __name__ == '__main__':
main()
And my setup.py file is this:
import sys
from cx_Freeze import setup, Executable
setup(
name = "On Dijkstra's Algorithm",
version = "3.1",
description = "A Dijkstra's Algorithm help tool.",
executables = [Executable("nautilus.py")])
I've the folder build but when I try to open th new exe file it returns me that error:
File "ExtensionLoader_PyQt4_QtGui.py", line 11, in <module>
ImportError: No module named atexit
Help please!
I'd try adding options = {"build_exe" : {"includes" : "atexit" }} to setup.py,
ref. https://bitbucket.org/reclosedev/cx_freeze/src/f3cacc2fd45a/samples/PyQt4/setup.py
Try something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore, QtWebKit, QtNetwork
class myWindow(QtWebKit.QWebView):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.setWindowTitle('Titanicus 0.1')
self.settings().setAttribute(QtWebKit.QWebSettings.JavascriptEnabled, True)
page = raw_input('Escriu una web: ')
self.load(QtCore.QUrl(page))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = myWindow()
main.show()
sys.exit(app.exec_())

Categories

Resources