I'm trying to create a Qt application that can communicate with R via PyQt and the rPython package and remain responsive while the R prompt is live.
Here's a minimal PyQt4 script that creates a button in a window that prints "clicked" when you click it.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class Ui_simple(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Test")
Dialog.resize(200,200)
self.pushButton = QPushButton(Dialog)
QObject.connect(self.pushButton, SIGNAL("clicked()"), self.clicked)
def clicked(self):
print "Clicked"
class main(object):
def __init__(self):
self.app = QApplication([])
self.Dialog = QDialog()
self.ui = Ui_simple()
self.ui.setupUi(self.Dialog)
self.Dialog.show()
When run from the Python prompt, the application becomes active when the QDialog object is created and shown. The python prompt returns. I can then exec_ the application object, and I get the prompt back when I quit the dialog:
>>> import simple
>>> a = simple.main()
>>> Clicked [python prompt is back now, I'm clicking the button]
Clicked
>>> a.app.exec_()
Clicked
This behaviour - of being interactive while also waiting for Python text prompt input - is because PyQt4 installs an input hook that waits for keyboard input and processes events.
What I want to do is have this same behaviour with Qt dialogs called from R via the rPython package. The following displays the dialog but it does not appear until the exec_ call, and the R prompt does not return until the application is exited by quitting the dialog window:
> require(rPython)
Loading required package: rPython
Loading required package: RJSONIO
> python.load("simple.py")
> python.exec("a = main()") # nothing happens
> python.exec("a.app.exec_()") # dialog appears, R blocked
Clicked
Clicked # click the buttons
Clicked
0 # kill window now
> # back to R prompt
A solution to my problem would involve the dialog appearing when running a=main() and the R prompt reappearing at that point too.
There are some Qt-based R packages that appear to create dialogs that remain interactive when the R prompt is active, but they are mostly in C and I'm not sure if that make a big difference. See qtutils for example.
There is some event loop handling in qtbase but I'm not sure if something like that is possible for Qt apps called from rPython. All ideas welcome.
Related
I'm embedding another window into a Qt widget using PySide2.QtGui.QWindow.fromWinId(windowId). It works well, but it does not fire an event when the the original X11 window destroys it.
If I run the file below with mousepad & python3 embed.py and press Ctrl+Q, no event fires and I'm left with an empty widget.
How can I detect when the X11 window imported by QWindow.fromWinId is destroyed by its creator?
#!/usr/bin/env python
# sudo apt install python3-pip
# pip3 install PySide2
import sys, subprocess, PySide2
from PySide2 import QtGui, QtWidgets, QtCore
class MyApp(QtCore.QObject):
def __init__(self):
super(MyApp, self).__init__()
# Get some external window's windowID
print("Click on a window to embed it")
windowIdStr = subprocess.check_output(['sh', '-c', """xwininfo -int | sed -ne 's/^.*Window id: \\([0-9]\\+\\).*$/\\1/p'"""]).decode('utf-8')
windowId = int(windowIdStr)
print("Embedding window with windowId=" + repr(windowId))
# Create a simple window frame
self.app = QtWidgets.QApplication(sys.argv)
self.mainWindow = QtWidgets.QMainWindow()
self.mainWindow.show()
# Grab the external window and put it inside our window frame
self.externalWindow = QtGui.QWindow.fromWinId(windowId)
self.externalWindow.setFlags(QtGui.Qt.FramelessWindowHint)
self.container = QtWidgets.QWidget.createWindowContainer(self.externalWindow)
self.mainWindow.setCentralWidget(self.container)
# Install event filters on all Qt objects
self.externalWindow.installEventFilter(self)
self.container.installEventFilter(self)
self.mainWindow.installEventFilter(self)
self.app.installEventFilter(self)
self.app.exec_()
def eventFilter(self, obj, event):
# Lots of events fire, but no the Close one
print(str(event.type()))
if event.type() == QtCore.QEvent.Close:
mainWindow.close()
return False
prevent_garbage_collection = MyApp()
Below is a simple demo script that shows how to detect when an embedded external window closes. The script is only intended to work on Linux/X11. To run it, you must have wmctrl installed. The solution itself doesn't rely on wmctrl at all: it's merely used to get the window ID from the process ID; I only used it in my demo script because its output is very easy to parse.
The actual solution relies on QProcess. This is used to start the external program, and its finished signal then notifies the main window that the program has closed. The intention is that this mechanism should replace your current approach of using subprocess and polling. The main limitation of both these approaches is they will not work with programs that run themselves as background tasks. However, I tested my script with a number applications on my Arch Linux system - including Inkscape, GIMP, GPicView, SciTE, Konsole and SMPlayer - and they all behaved as expected (i.e. they closed the container window when exiting).
NB: for the demo script to work properly, it may be necessary to disable splash-screens and such like in some programs so they can embed themselves correctly. For example, GIMP must be run like this:
$ python demo_script.py gimp -s
If the script complains that it can't find the program ID, that probably means the program launched itself as a background task, so you will have to try to find some way to force it into the foreground.
Disclaimer: The above solution may work on other platforms, but I have not tested it there, and so cannot offer any guarantees. I also cannot guarantee that it will work with all programs on Linux/X11.
I should also point out that embedding external, third-party windows is not officially supported by Qt. The createWindowContainer function is only intended to work with Qt window IDs, so the behaviour with foreign window IDs is strictly undefined (see: QTBUG-44404). The various issues are documentented in this wiki article: Qt and foreign windows. In particular, it states:
A larger issue with our current APIs, that hasn't been discussed yet,
is the fact that QWindow::fromWinId() returns a QWindow pointer, which
from an API contract point of view should support any operation that
any other QWindow supports, including using setters to manipulate the
window, and connecting to signals to observe changes to the window.
This contract is not adhered to in practice by any of our platforms,
and the documentation for QWindow::fromWinId() doesn't mention
anything about the situation.
The reasons for this undefined/platform specific behaviour largely
boils down to our platforms relying on having full control of the
native window handle, and the native window handle often being a
subclass of the native window handle type, where we implement
callbacks and other logic. When replacing the native window handle
with an instance we don't control, and which doesn't implement our
callback logic, the behaviour becomes undefined and full of holes
compared to a regular QWindow.
So, please bear all that in mind when designing an application that relies on this functionality, and adjust your expectations accordingly...
The Demo script:
import sys, os, shutil
from PySide2.QtCore import (
Qt, QProcess, QTimer,
)
from PySide2.QtGui import (
QWindow,
)
from PySide2.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QMessageBox,
)
class Window(QWidget):
def __init__(self, program, arguments):
super().__init__()
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
self.external = QProcess(self)
self.external.start(program, arguments)
self.wmctrl = QProcess()
self.wmctrl.setProgram('wmctrl')
self.wmctrl.setArguments(['-lpx'])
self.wmctrl.readyReadStandardOutput.connect(self.handleReadStdOut)
self.timer = QTimer(self)
self.timer.setSingleShot(True)
self.timer.setInterval(25)
self.timer.timeout.connect(self.wmctrl.start)
self.timer.start()
self._tries = 0
def closeEvent(self, event):
for process in self.external, self.wmctrl:
process.terminate()
process.waitForFinished(1000)
def embedWindow(self, wid):
window = QWindow.fromWinId(wid)
widget = QWidget.createWindowContainer(
window, self, Qt.FramelessWindowHint)
self.layout().addWidget(widget)
def handleReadStdOut(self):
pid = self.external.processId()
if pid > 0:
windows = {}
for line in bytes(self.wmctrl.readAll()).decode().splitlines():
columns = line.split(maxsplit=5)
# print(columns)
# wid, desktop, pid, wmclass, client, title
windows[int(columns[2])] = int(columns[0], 16)
if pid in windows:
self.embedWindow(windows[pid])
# this is where the magic happens...
self.external.finished.connect(self.close)
elif self._tries < 100:
self._tries += 1
self.timer.start()
else:
QMessageBox.warning(self, 'Error',
'Could not find WID for PID: %s' % pid)
else:
QMessageBox.warning(self, 'Error',
'Could not find PID for: %r' % self.external.program())
if __name__ == '__main__':
if len(sys.argv) > 1:
if shutil.which(sys.argv[1]):
app = QApplication(sys.argv)
window = Window(sys.argv[1], sys.argv[2:])
window.setGeometry(100, 100, 800, 600)
window.show()
sys.exit(app.exec_())
else:
print('could not find program: %r' % sys.argv[1])
else:
print('usage: python %s <external-program-name> [args]' %
os.path.basename(__file__))
I'm developing an GUI for multi-robot system using ROS, but i'm freezing in the last thing i want in my interface: embedding the RVIZ, GMAPPING or another screen in my application. I already put an terminal in the interface, but i can't get around of how to add an external application window to my app. I know that PyQt5 have the createWindowContainer, with uses the window ID to dock an external application, but i didn't find any example to help me with that.
If possible, i would like to drag and drop an external window inside of a tabbed frame in my application. But, if this is not possible or is too hard, i'm good with only opening the window inside a tabbed frame after the click of a button.
I already tried to open the window similar to the terminal approach (see the code bellow), but the RVIZ window opens outside of my app.
Already tried to translate the attaching/detaching code code to linux using the wmctrl command, but didn't work wither. See my code here.
Also already tried the rviz Python Tutorial but i'm receveing the error:
Traceback (most recent call last):
File "rvizTutorial.py", line 23, in
import rviz
File "/opt/ros/indigo/lib/python2.7/dist-packages/rviz/init.py", line 19, in
import librviz_shiboken
ImportError: No module named librviz_shiboken
# Frame where i want to open the external Window embedded
self.Simulation = QtWidgets.QTabWidget(self.Base)
self.Simulation.setGeometry(QtCore.QRect(121, 95, 940, 367))
self.Simulation.setTabPosition(QtWidgets.QTabWidget.North)
self.Simulation.setObjectName("Simulation")
self.SimulationFrame = QtWidgets.QWidget()
self.SimulationFrame.setObjectName("SimulationFrame")
self.Simulation.addTab(rviz(), "rViz")
# Simulation Approach like Terminal
class rviz(QtWidgets.QWidget):
def __init__(self, parent=None):
super(rviz, self).__init__(parent)
self.process = QtCore.QProcess(self)
self.rvizProcess = QtWidgets.QWidget(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.rvizProcess)
# Works also with urxvt:
self.process.start('rViz', [str(int(self.winId()))])
self.setGeometry(121, 95, 940, 367)
I've not tested this specifically, as I've an old version of Qt5 I can't upgrade right now, while from Qt5 5.10 startDetached also returns the pid along with the bool result from the started process.
In my tests I manually set the procId (through a static QInputBox.getInt()) before starting the while cycle that waits for the window to be created.
Obviously there are other ways to do this (and to get the xid of the window).
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import gi
gi.require_version('Wnck', '3.0')
from gi.repository import Wnck, Gdk
class Container(QtWidgets.QTabWidget):
def __init__(self):
QtWidgets.QTabWidget.__init__(self)
self.embed('xterm')
def embed(self, command, *args):
proc = QtCore.QProcess()
proc.setProgram(command)
proc.setArguments(args)
started, procId = proc.startDetached()
if not started:
QtWidgets.QMessageBox.critical(self, 'Command "{}" not started!')
return
attempts = 0
while attempts < 10:
screen = Wnck.Screen.get_default()
screen.force_update()
# this is required to ensure that newly mapped window get listed.
while Gdk.events_pending():
Gdk.event_get()
for w in screen.get_windows():
if w.get_pid() == procId:
window = QtGui.QWindow.fromWinId(w.get_xid())
container = QtWidgets.QWidget.createWindowContainer(window, self)
self.addTab(container, command)
return
attempts += 1
QtWidgets.QMessageBox.critical(self, 'Window not found', 'Process started but window not found')
app = QtWidgets.QApplication(sys.argv)
w = Container()
w.show()
sys.exit(app.exec_())
I couldn't get the code in the accepted answer to work on Ubuntu 18.04.3 LTS; even when I got rid of the exceptions preventing the code to run, I'd still get a separate PyQt5 window, and separate xterm window.
Finally after some tries, I got the xterm window to open inside the tab; here is my code working in Ubuntu 18.04.3 LTS (with all the misses commented):
#!/usr/bin/env python3
# (same code seems to run both with python3 and python2 with PyQt5 in Ubuntu 18.04.3 LTS)
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import gi
gi.require_version('Wnck', '3.0')
from gi.repository import Wnck, Gdk
import time
class Container(QtWidgets.QTabWidget):
def __init__(self):
QtWidgets.QTabWidget.__init__(self)
self.embed('xterm')
def embed(self, command, *args):
proc = QtCore.QProcess()
proc.setProgram(command)
proc.setArguments(args)
#started, procId = proc.startDetached()
#pid = None
#started = proc.startDetached(pid)
# https://stackoverflow.com/q/31519215 : "overload" startDetached : give three arguments, get a tuple(boolean,PID)
# NB: we will get a failure `xterm: No absolute path found for shell: .` even if we give it an empty string as second argument; must be a proper abs path to a shell
started, procId = proc.startDetached(command, ["/bin/bash"], ".")
if not started:
QtWidgets.QMessageBox.critical(self, 'Command "{}" not started!'.format(command), "Eh")
return
attempts = 0
while attempts < 10:
screen = Wnck.Screen.get_default()
screen.force_update()
# do a bit of sleep, else window is not really found
time.sleep(0.1)
# this is required to ensure that newly mapped window get listed.
while Gdk.events_pending():
Gdk.event_get()
for w in screen.get_windows():
print(attempts, w.get_pid(), procId, w.get_pid() == procId)
if w.get_pid() == procId:
self.window = QtGui.QWindow.fromWinId(w.get_xid())
#container = QtWidgets.QWidget.createWindowContainer(window, self)
proc.setParent(self)
#self.scrollarea = QtWidgets.QScrollArea()
#self.container = QtWidgets.QWidget.createWindowContainer(self.window)
# via https://vimsky.com/zh-tw/examples/detail/python-method-PyQt5.QtCore.QProcess.html
#pid = proc.pid()
#win32w = QtGui.QWindow.fromWinId(pid) # nope, broken window
win32w = QtGui.QWindow.fromWinId(w.get_xid()) # this finally works
win32w.setFlags(QtCore.Qt.FramelessWindowHint)
widg = QtWidgets.QWidget.createWindowContainer(win32w)
#self.container.layout = QtWidgets.QVBoxLayout(self)
#self.addTab(self.container, command)
self.addTab(widg, command)
#self.scrollarea.setWidget(self.container)
#self.container.setParent(self.scrollarea)
#self.scrollarea.setWidgetResizable(True)
#self.scrollarea.setFixedHeight(400)
#self.addTab(self.scrollarea, command)
self.resize(500, 400) # set initial size of window
return
attempts += 1
QtWidgets.QMessageBox.critical(self, 'Window not found', 'Process started but window not found')
app = QtWidgets.QApplication(sys.argv)
w = Container()
w.show()
sys.exit(app.exec_())
I've been trying to do animation with VTK, so I've been using TimerEvent. When I tried to move over to the Qt binding, it broke. The problem is that as soon as I interact with the view (say scrolling to zoom, or clicking to rotate) the timer stops. Here's a simple minimal example:
import vtk
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt5 import Qt
message = "tick"
def onTimerEvent(object, event):
global message
print(message)
if message == "tick":
message = "tock"
else:
message = "tick"
app = Qt.QApplication([])
mainWindow = Qt.QMainWindow()
renderer = vtk.vtkRenderer()
vtkWidget = QVTKRenderWindowInteractor(mainWindow)
vtkWidget.GetRenderWindow().AddRenderer(renderer)
mainWindow.setCentralWidget(vtkWidget)
vtkWidget.GetRenderWindow().GetInteractor().Initialize()
timerId = vtkWidget.CreateRepeatingTimer(100)
vtkWidget.AddObserver("TimerEvent", onTimerEvent)
mainWindow.show()
app.exec_()
This script should display the words "tick" and "tock" over and over again, but stop as soon as you click inside the window.
One odd behavior is that pressing "T" to switch to trackball interaction style seems to have some effect. If I press T and then click inside the window, the timer only stops running while I'm clicking: when I let go it starts up again. If I then press J to go back to "joystick mode", the problem returns: clicking stops the timer forever.
Python 3.6, VTK 8, Qt 5.
The problem is reproducible in Linux 16.04, VTK8.1.1 and Qt5.5.1.
As you are using Qt, a workaround for your problem is to use QTimer(). It is a solution if you want to work with a timing.
This is your minimal example changing the TimerEvent for QTimer():
import vtk
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt5 import Qt
from PyQt5.QtCore import QTimer
message = "tick"
def onTimerEvent():
global message
print(message)
if message == "tick":
message = "tock"
else:
message = "tick"
app = Qt.QApplication([])
mainWindow = Qt.QMainWindow()
renderer = vtk.vtkRenderer()
vtkWidget = QVTKRenderWindowInteractor(mainWindow)
vtkWidget.GetRenderWindow().AddRenderer(renderer)
mainWindow.setCentralWidget(vtkWidget)
vtkWidget.GetRenderWindow().GetInteractor().Initialize()
#timerId = vtkWidget.CreateRepeatingTimer(100)
#vtkWidget.AddObserver("TimerEvent", onTimerEvent)
timer = QTimer()
timer.timeout.connect(onTimerEvent)
timer.start(100)
mainWindow.show()
app.exec_()
I'm trying to create an application that contains a web browser within it, but when I add the web browser my menu bar visually disappears but functionally remains in place. The following are two images, one showing the "self.centralWidget(self.web_widget)" commented out, and the other allows that line to run. If you run the example code, you will also see that while visually the entire web page appears as if the menu bar wasn't present, you have to click slightly below each entry field and button in order to activate it, behaving as if the menu bar was in fact present.
Web Widget Commented Out
Web Widget Active
Example Code
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
class WebPage(QWebEngineView):
def __init__(self, parent=None):
QWebEngineView.__init__(self)
self.current_url = ''
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
def _on_load_finished(self):
print("Url Loaded")
class MainWindow(QMainWindow):
def __init__(self, parent=None):
# Initialize the Main Window
super(MainWindow, self).__init__(parent)
self.create_menu()
self.add_web_widet()
self.show()
def create_menu(self):
''' Creates the Main Menu '''
self.main_menu = self.menuBar()
self.main_menu_actions = {}
self.file_menu = self.main_menu.addMenu("Example File Menu")
self.file_menu.addAction(QAction("Testing Testing", self))
def add_web_widet(self):
self.web_widget = WebPage(self)
self.setCentralWidget(self.web_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.showMaximized()
sys.exit(app.exec_()) # only need one app, one running event loop
Development Environment
Windows 10, PyQt5, pyqt5-5.9
EDIT
The problem doesn't seem to be directly related to the menu bar. Even removing the menu bar the issue still occurs. That said, changing from showMaximized() to showFullScreen() does seem to solve the problem.
I no longer believe this is an issue with PyQt5 specifically but rather a problem with the graphics driver. Specifically, if you look at Atlassian's HipChat application it has a similar problem which is documented here:
https://jira.atlassian.com/browse/HCPUB-3177
Some individuals were able to solve the problem by running the application from the command prompt with the addendum "--disable-gpu" but that didn't work for my python application. On the other hand, rolling back the Intel(R) HD Graphics Driver did solve my problem. Version 21.20.16.4627 is the one that seems to be causing problems.
I have a simple script primarily based on QSystemTrayIcon. Everything works find, and there's an option there on right-click on the taskbar icon that exits the program. I would like to add a QMessageBox, and on choosing yes, exit the program; otherwise, do nothing.
I'm familiar with all that, but it doesn't work as it should, and hence the question. I created a minimal example to demonstrate the problem:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
self.menu = QtWidgets.QMenu(parent)
self.exit_action = self.menu.addAction("Exit")
self.setContextMenu(self.menu)
self.exit_action.triggered.connect(self.slot_exit)
self.msg_parent = QtWidgets.QWidget()
def slot_exit(self):
reply = QtWidgets.QMessageBox.question(self.msg_parent, "Confirm exit",
"Are you sure you want to exit Persistent Launcher?",
QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
# if reply == QtWidgets.QMessageBox.Yes:
# QtCore.QCoreApplication.exit(0)
def main():
app = QtWidgets.QApplication(sys.argv)
tray_icon = SystemTrayIcon(QtGui.QIcon("TheIcon.png"))
tray_icon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Now you see, at the slot_exit() function, whether I choose yes or no, the program exits (with code 0, no errors). The commented part is what I expect to be used to determine the action based on the choice. Could you please help me figure out why this behavior is happening and what's the right way to exit only on "yes"?
I'm using Windows 10, 64-bit with Python Anaconda 3.5.2 32-bit, and PyQt 5.7.
The problem is that Qt is made to exit when all Windows are closed. Simply disable that with:
app.setQuitOnLastWindowClosed(False)
in your main().