I'm new to PyQt4 and I have 2 questions.
I want to create a GUI by which for example when I press a button, a terminal command run (e.g. ping www.google.com)
can I import cvlc in part of GUI
to wrap up I want to create a GUI in which when I press a button
cvlc -v v4l2:///dev/video0
runs and the cvlc window is shown in the GUI.
Any help would be appreciated
This will solve first part i.e. when ping button is pressed it pings google.com and the output is displayed on a terminal.
import sys,os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(150, 150, 150,150)
self.ping = QPushButton('Press to ping', self)
self.ping.move(10,20)
self.ping.clicked.connect(self.gotoPing)
def gotoPing(self):
os.system("ping www.google.com")
def main():
app = QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Related
Button click starts a new detached process of the same app. However, when launched from PyCharm, it crashes on second restart. Print is no longer visible after restart as well.
I want my app to be able to restart many times when launched from either PyCharm or cmd.
import sys, os
from PyQt5.QtCore import QProcess
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
button = QPushButton("Restart")
button.clicked.connect(self.restart)
self.setCentralWidget(button)
def restart(self):
print("Restart")
self.close()
proc = QProcess()
proc.startDetached(sys.executable, sys.argv)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
if __name__ == "__main__":
main()
I need to display adb logs in a Pyqt window, i tried like this. When i click the button log_display function is called, which set the console output to textBrowser. I tried to use subprocess but it didn't help, the window is just freezing and not responding. What is the way to do it? Maybe i need to use new thread for it?
def log_display(self):
result = subprocess.run('adb logcat *:I', stdout=subprocess.PIPE)
self.textBrowser.setText(subprocess.run('result.stdout'))
You have to use QProcess since it launches the application but does not block the GUI since it notifies the log through signals:
from PyQt5 import QtCore, QtGui, QtWidgets
class LogView(QtWidgets.QPlainTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setReadOnly(True)
self._process = QtCore.QProcess()
self._process.readyReadStandardOutput.connect(self.handle_stdout)
self._process.readyReadStandardError.connect(self.handle_stderr)
def start_log(self, program, arguments=None):
if arguments is None:
arguments = []
self._process.start(program, arguments)
def add_log(self, message):
self.appendPlainText(message.rstrip())
def handle_stdout(self):
message = self._process.readAllStandardOutput().data().decode()
self.add_log(message)
def handle_stderr(self):
message = self._process.readAllStandardError().data().decode()
self.add_log(message)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = LogView()
w.resize(640, 480)
w.show()
w.start_log("adb", ["logcat", "*:I"])
sys.exit(app.exec_())
I'm running a Qt5 application with a main application window and trying to show a progress dialog window. I have a multi screen system, when starting the application the main window is displayed on the screen where it has been executed which is fine, but the progress dialog when executed is shown on a different screen!?
Here is a simple example code that causes the problem for me
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class Example(QMainWindow):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self._show_progress()
def _show_progress(self):
self._progress = QProgressDialog('msg', None, 0, 0, self)
self._progress.setWindowTitle('Please wait...')
self._progress.setWindowModality(Qt.WindowModal)
self._progress.show()
def main():
app = QApplication(sys.argv)
cb_app = Example()
cb_app.show()
app.exec_()
if __name__ == '__main__':
main()
Can I somehow specify where the the dialog should be shown (ideally on top of the main window)?
I'm using Linux Mint 18.2, window manager X-Cinnamon and PyQt version 5.5.1
I have a small script that is designed to embed an xterm in a PyQt GUI. On Linux, it works, creating a GUI like this:
However, running the same script on OS X yields two windows like this:
Does anyone know how to address this and prevent OS X from screwing up the GUI?
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class embeddedTerminal(QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(800, 600)
self.process = QProcess(self)
self.terminal = QWidget(self)
layout = QVBoxLayout(self)
layout.addWidget(self.terminal)
self.process.start('xterm', ['-into', str(self.terminal.winId())])
if __name__ == "__main__":
app = QApplication(sys.argv)
main = embeddedTerminal()
main.show()
sys.exit(app.exec_())
You could take a look at the qtconsole front end for Jupyter and try to use the bash kernel. Depending on your end goal, I know it is possible to embed an IPython kernel, in another application.
I am wondering how one would create a GUI application, and interact with it from the console that started it.
As an example, I would like to create a GUI in PyQt and work with it from the console. This could be for testing settings without restarting the app, but in larger projects also for calling functions etc.
Here is a simple example using PyQt:
import sys
from PyQt4 import QtGui
def main():
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
when this is run with python -i example.py the console is blocked as long as the main-loop is executed.
How can I call w.resize(100,100) while the GUI is running?
ops, posted wrong answer before
there is a post in Stack about that
Execute Python code from within PyQt event loop
The following example uses the code module to run a console in the command prompt (be sure to run the script from the command line). Subclassing QThread provides a route by which the console can be run in a separate thread from that of the main GUI and enables some interaction with it. The stub example below should be easy enough to incorporate into a larger packaged PyQt program.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import threading #used only to id the active thread
import code
import sys
class Worker(QThread): #Subclass QThread and re-define run()
signal = pyqtSignal()
def __init__(self):
super().__init__()
def raise_sys_exit(self): #more gracefully exit the console
print('(Deactivated Console)')
raise SystemExit
def setup_console(self,global_dict):
console_exit = {'exit': self.raise_sys_exit}
self.console = code.InteractiveConsole(locals=dict(global_dict,**console_exit))
def run(self):
try:
print('worker', threading.get_ident())
self.console.interact()
except SystemExit:
self.signal.emit()
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args,**kwargs)
self.data = [1,2,3,4] #some data we might want to look at
layout = QVBoxLayout()
self.b = QPushButton("Interact")
self.b.clicked.connect(self.b_clicked)
layout.addWidget(self.b)
w = QWidget()
w.setLayout(layout)
self.setCentralWidget(w)
self.worker = Worker()
self.worker.signal.connect(self.finished)
def finished(self):
self.b.setEnabled(True)
def b_clicked(self):
print('main',threading.get_ident())
self.worker.setup_console(globals()) #pass the global variables to the worker
self.worker.start()
self.b.setEnabled(False) #disable the GUI button until console is exited
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
The easiest way is to use IPython:
ipython --gui=qt4
See ipython --help or the online documentation for more options (e.g. gtk, tk, etc).