How to display an SVG image in Python - python

I was following this tutorial on how to write a chess program in Python.
It uses the python-chess engine. The functions from that engine apparently return SVG data, that could be used to display a chessboard.
Code from the tutorial:
import chess
import chess.svg
from IPython.display import SVG
board = chess.Board()
SVG(chess.svg.board(board=board,size=400))
but when I run that code, all I see is a line in the terminal and no image.
<IPython.core.display.SVG object>
The tutorial makes a passing reference to Jupyter Notebooks and how they can be used to display SVG images. I have no experience with Jupyter Notebooks and even though I installed the package from pip and I dabbled a little into how to use it, I couldn't make much progress with regards to my original chessboard problem. But what I do have, is, experience with Qt development using C++ and since Qt has Python bindings, I decided to use those bindings.
Here is what I wrote:
import sys
import chess
import chess.svg
from PyQt5 import QtGui, QtSvg
from PyQt5.QtWidgets import QApplication
from IPython.display import SVG, display
app = QApplication(sys.argv);
board = chess.Board();
svgWidget = QtSvg.QSvgWidget(chess.svg.board(board=board, size=400));
#svgWidget.setGeometry(50,50,759,668)
svgWidget.show()
sys.exit(app.exec_())
A Qt window opens and shows nothing and in the terminal I see a lot of text - (apparently the SVG data is ending up in the console and not in the Qt window that is opening?).
I figured I have to install some SVG library under python so I installed drawSvg from pip. But it seems that library generates SVG images. And was of no use for me.
What is even more strange is, after seeing this SO question, I tried the following:
import sys
import chess
import chess.svg
from PyQt5 import QtGui, QtSvg
from PyQt5.QtWidgets import QApplication
from IPython.display import SVG, display
app = QApplication(sys.argv);
board = chess.Board();
svgWidget = QtSvg.QSvgWidget('d:\projects\python_chess\Zeichen_123.svg');
#svgWidget.setGeometry(50,50,759,668)
svgWidget.show()
sys.exit(app.exec_())
And it showed an image - an SVG image! What is the difference then between my case and this case?
Question: So my question is, what I am doing wrong in the case of the chessboard SVG data? Is the SVG data generated by the python-chess library not compatible with QtSvg?

I think you are getting confused by the scripting nature of Python. You say, you have experience with Qt development under C++. Wouldn't you create a main window widget there first and add to it your SVG widget within which you would call or load SVG data?
I would rewrite your code something like this.
import chess
import chess.svg
from PyQt5.QtSvg import QSvgWidget
from PyQt5.QtWidgets import QApplication, QWidget
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 1100, 1100)
self.widgetSvg = QSvgWidget(parent=self)
self.widgetSvg.setGeometry(10, 10, 1080, 1080)
self.chessboard = chess.Board()
self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
self.widgetSvg.load(self.chessboardSvg)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
EDIT
It would be even better if you would add a paint function to the MainWindow class. Because for sure in future, you would want to repaint your board image many times, whenever you would move a piece. So I would do something like this.
def paintEvent(self, event):
self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8")
self.widgetSvg.load(self.chessboardSvg)

this is how i display SVG image with python, no need third party to do that.
First i save SVG image on disk
second i just call it like os.Startfile("exemple.svg")
Exemple:
boardsvg = svg.board(board(fen), size=600, coordinates=True)
with open('temp.svg', 'w') as outputfile:
outputfile.write(boardsvg)
time.sleep(0.1)
os.startfile('temp.svg')
that's it !

Related

PyInstaller generated exe file error : qt.qpa.plugin: could not load the qt platform plugin "windows" in "" even though it was found

I have created a program to read certain data from files on a drive, display results on a PyQt5 ui and accept corrections if any from user.
The program worked fine when run as a python file. However, when i converted it into a standalone exe using PyInstaller, it works fine upto the point where the pyqt5 gui needs to be launched. At this point, it stops throwing the following error :
qt.qpa.plugin: Could not load the Qt platform plugin "windows" in "" even though it was found. This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Available platform plugins are: minimal, offscreen, windows.
I have read this, this and this but they dont resolve my issue.
The code of the gui is very big but here is the structure :
from PyQt5 import uic, QtWidgets
import sys
import os
#baseUIClass, baseUIWidget = uic.loadUiType('gui.ui')
baseUIClass, baseUIWidget = uic.loadUiType(r'C:\mypath\gui.ui')
class Ui(baseUIClass, baseUIWidget ):
def __init__(self, *args, **kwargs):
baseUIWidget.__init__(self, *args, **kwargs)
self.setupUi(self)
# More code to perform the desired actions
def run(input_variables):
app = QtWidgets.QApplication(sys.argv)
ui = Ui()
ui.show()
# More code to make the Ui perform desired actions
app.exec_()
return(output_variables)
The code was converted to a standalone exe with the following arguments :
pyinstaller --hiddenimport <hidden import> --onefile <python filename>
Would you know how to troubleshoot this please?
Thanks
I ran into the same error message with my compiled application.
To track down the issue, I first stripped down the app to its skeleton with minimal imports, which worked flawlessly when compiled. I then partially added back all imports of my "big" application until the error reappeared.
In the end (for me at least) pandas is the culprit:
Minimal reproducibale examples, this works:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
window.show()
app.exec()
This (added pandas import in line 2) throws the error you describe:
from PyQt5 import QtWidgets
import pandas as pd # import after pyqt5
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
window.show()
app.exec()
However, when first importing pandas and then importing PyQt 5, my compiled version works again:
import pandas as pd # import before pyqt5
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QMainWindow()
window.show()
app.exec()
So, in my case the solution was to track down the "erroneous import", fiddle with the import order and get lucky (I am far too unexperienced to even try to understand why the import order leads to this error)
If you are not using pandas, maybe the whole "strip down to skeleton and start importing piece by piece"-approach will help you to further clarify the root cause of the error.
If you are using pandas and the order switch-up did not help, there is another thread which describes which tries to deal with pandas compiling issues.

PyQt setText not rendering text properly in MacOs

I am creating an application using PyQt5 (pythyon 3.7 , MacOs X)
When I modify the text in a textbox using the instruction
self.line_main.setText(final_text)
from a function (which is connected to a push button)
The new text does not render properly in the textbox (see screenshot) and both the old and new text are overlapping in a strange way.
An over-simplified code to illustrate the problem is this one:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(200, 200))
self.setWindowTitle("PyQt test")
self.line_main = QLineEdit(self)
self.line_main.move(20,20)
bt_upperCase = QPushButton('Upper Case', self)
bt_upperCase.move(20, 60)
bt_upperCase.clicked.connect(self.click_upCase)
def click_upCase(self):
final_text=self.line_main.text().upper()
self.line_main.setText(final_text)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit( app.exec_() )
screenshot of mini-app, with 're' as input as 'RE' as output
The same thing may happen for labels, although at times, only the old text is visible, and I need to select the text with the mouse or resize the main window to 'refresh' the textbox and see the new value.
The problem does not happen if I run the code in a PC, only in MacOs (tested in High Sierra and Mojave with identical results)
Some weird behaviours are:
If position the textbox at the (0,0) position in the main window, which is not very practical, then the setText functions correctly. In some other locations of the box, too, but only if it is very close to the top-left corner, and no other element is near.
If I modify the textbox value at the initialization of the main window, then it renders correctly in all cases, The problem appears when you try to do it from a function (after clicking a button, for instance), like in the code attached.
The problem does not happen if I run the code in a PC, only in MacOs (tested in High Sierra and Mojave with identical results)
If position the textbox at the (0,0) position in the main window, (which is not very practical), then the setText functions correctly. In some other locations of the box, too, but only if it is very close to the top-left corner, and no other element is near.
Does anyone have a guess why this may happen, and how could it be solved?
UPDATE.
The problem dissapears if i run the code with python 3.6 in a conda installation (PyQt version 5.9.2). Still very intrigued to know what caused the problem.

Python: matplotlib plot inside QML layout

Consider the following python3 PyQt code to display an interactive matplotlib graph with toolbar
import sys, sip
import numpy as np
from PyQt5 import QtGui, QtWidgets
from PyQt5.Qt import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
app = QApplication(sys.argv)
top = QWidget()
fig = plt.figure()
ax = fig.gca()
x = np.linspace(0,5,100)
ax.plot(x,np.sin(x))
canvas = FigureCanvas(fig)
toolbar = NavigationToolbar(canvas, top)
def pick(event):
if (event.xdata is None) or (event.ydata is None): return
ax.plot([0,event.xdata],[0,event.ydata])
canvas.draw()
canvas.mpl_connect('button_press_event', pick)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(toolbar)
layout.addWidget(canvas)
top.setLayout(layout)
top.show()
app.exec_()
Now I'd like to achieve the same by using PyQt with QML instead. I have some experience with creating QML GUIs in C++ and I really like the fact that the layout code is nicely separated from the core logic of the code.
I have found several examples on how to show plots in PyQt and on how to use Python with QML, but nothing that combines the two.
To start off, my python and QML snippets look as follows:
Python:
import sys, sip
import numpy as np
from PyQt5 import QtGui, QtWidgets
from PyQt5.Qt import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(QUrl('layout.qml'))
root = engine.rootObjects()[0]
root.show()
sys.exit(app.exec_())
Layout:
import QtQuick 2.7
import QtQuick.Controls 1.4
ApplicationWindow {
visible: true
width: 400
height: 400
Canvas {
// canvas may not be the right choice here
id: mycanvas
anchors.fill: parent
}
}
But I am quite lost on how to continue.
More concretely, the question would be: Is there a way to display an interactive matplotlib plot in QML (by interactive I mean not just a figure that has been saved as an image, ideally with the standard toolbar for zoom etc.)
Can anyone help? Or is the combination of QML and plots just simply discouraged (this question suggests python and QML should work together quite well)?
I don't have a full solution, but if you're OK with just displaying charts and the fact that you'll have to provide any interactive controls by yourself, then there's a reasonably simple way to do that.
First of all, you will need to convert your matplotlib chart into a QImage. Fortunately doing so is surprisingly easy. The canonical backend (renderer) for matplotlib is *Agg`, and it allows you to render your Figure into a memory. Just make a suitable Canvas object for you Figure, then call .draw(). The QImage constructor will take generated data directly as inputs.
canvas = FigureCanvasAgg(figure)
canvas.draw()
img = QtGui.QImage(canvas.buffer_rgba(), *canvas.get_width_height(), QtGui.QImage.Format_RGBA8888).copy()
The Qt way to provide that image into QML is to use QQuickImageProvider. It will get "image name" as input from QML and should provide a suitable image as output. This allows you to serve all matplotlib charts in your app with just one Image provider. When I was working on a small visualization app for internal use, I ended up with a code like this:
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import PyQt5.QtQuick as QtQuick
import PyQt5.QtQml as QtQml
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
class MatplotlibImageProvider(QtQuick.QQuickImageProvider):
figures = dict()
def __init__(self):
QtQuick.QQuickImageProvider.__init__(self, QtQml.QQmlImageProviderBase.Image)
def addFigure(self, name, **kwargs):
figure = Figure(**kwargs)
self.figures[name] = figure
return figure
def getFigure(self, name):
return self.figures.get(name, None)
def requestImage(self, p_str, size):
figure = self.getFigure(p_str)
if figure is None:
return QtQuick.QQuickImageProvider.requestImage(self, p_str, size)
canvas = FigureCanvasAgg(figure)
canvas.draw()
w, h = canvas.get_width_height()
img = QtGui.QImage(canvas.buffer_rgba(), w, h, QtGui.QImage.Format_RGBA8888).copy()
return img, img.size()
Whenever I need to draw a plot in python code, I just create Figure using this addFigure to give it a name and let the Qt to know about it. Once you got Figure, rest of matplotlib drawing happens exactly as usual. Make axes and plot.
self.imageProvider = MatplotlibImageProvider()
figure = self.imageProvider.addFigure("eventStatisticsPlot", figsize=(10,10))
ax = figure.add_subplot(111)
ax.plot(x,y)
Then in QML code I can simply refer matplotlib image by name ("eventStatisticsPlot")
Image {
source: "image://perflog/eventStatisticsPlot"
}
Note that URL is prefixed by "image://" to tell QML that we need to get image from QQuickImageProvider and includes name ("perflog") of a particular provider to use. For this stuff to work we need to register our provider during QML initialization with a call to addImageProvider. For example,
engine = QtQml.QQmlApplicationEngine()
engine.addImageProvider('perflog', qt_model.imageProvider)
engine.load(QtCore.QUrl("PerflogViewer.qml"))
At this point you should be able to see static graphs shown, but they will not be updated properly because Image component in QML assumes that image that we provide does not change. I found no good solution for it, but an ugly workaround is fairly simple. I added a signal called eventStatisticsPlotChanged to my helper class that exposes Python app data to QML and .emit() it whenever the relevant plot is changed. E.g. here's a chunk of code where I get data from QML on a time interval selected by user.
#QtCore.pyqtSlot(float, float)
def selectTimeRange(self, min_time, max_time):
self.selectedTimeRange = (min_time, max_time)
_, ax, _ = self.eventStatisticsPlotElements
ax.set_xlim(*self.selectedTimeRange)
self.eventStatisticsPlotChanged.emit()
See that .emit() in the end? In QML this event forces image to reload URL like this:
Image {
source: "image://perflog/eventStatisticsPlot"
cache: false
function reload() { var t = source; source = ""; source = t; }
}
Connections {
target: myDataSourceObjectExposedFromPython
onEventStatisticsPlotChanged: eventStatisticsPlot.reload()
}
So whenever user moves a control, following happens:
QML sends updated time interval to my data source via selectTimeRange() call
My code calls .set_xlim on appopriate matplotlib object and emit() a signal to notify QML that chart changed
QML queries my imageProvider for updated chart image
My code renders matplotlib chart into new QImage with Agg and passes it to Qt
QML shows that image to user
It might sound a bit complicated, but its actually easy to design and use.
Here's an example of how all this looks in our small visualization app. That's pure Python + QML, with pandas used to organize data and matplotlib to show it. Scroll-like element on bottom of the screen essentially redraws chart on every event and it happens so fast that it feels real-time.
I also tried to use SVG as a way to feed vector image into QML. It's also possible and it also works. Matplotlib offers SVG backend (matplotlib.backends.backend_svg) and Image QML component support inline SVG data as a Source. The SVG data is text so it can be easily passed around between python and QML. You can update (source) field with new data and image will redraw itself automatically, you can rely on data binding. It could've worked quite well, but sadly SVG support in Qt 4 and 5 is poor. Clipping is not supported (charts will go out of the axes); resizing Image does not re-render SVG but resizes pixel image of it; changing SVG causes image to blink; performance is poor. Maybe this will change one day later, but for now stick to agg backend.
I really love design of both matlpotlib and Qt. It's smart and it meshes well without too much effort or boilerplate code.
It's in a fairly basic state, but https://github.com/jmitrevs/matplotlib_backend_qtquick provides a workable model to start from.
To quickly summarize the gist of the example provided with it:
The library provides the types FigureCanvasQtQuickAgg and NavigationToolbar2QtQuick.
The FigureCanvasQtQuickAgg type is registered with QML:
QtQml.qmlRegisterType(FigureCanvasQtQuickAgg, "Backend", 1, 0, "FigureCanvas")
This allows you to use it from within QML:
FigureCanvas {
id: mplView
objectName : "figure"
dpi_ratio: Screen.devicePixelRatio
anchors.fill: parent
}
The objectName property allows the canvas instance to be found from within the Python code.
The toolbar is made out of QML buttons,
In the demo, they provide a DisplayBridge Python class that is linked to the canvas and is responsible for the actual plotting and for forwarding events from the various toolbar buttons
Internally, the FigureCanvasQtQuickAgg backend is a QQuickPaintedItem. In its paint function it copies data from the renderer attribute of the matplotlib FigureCanvasAgg base class into a QImage and the QImage is then painted. This is a fairly similar design to how the QWidget version of matplotlib works.

pyQt with interactive SVG images

How would I go about adding an interactive SVG file to a QGraphicsScene? I can add an interactive SVG file, but it's just displayed as a static image. I was reading about QGraphicsWebView but can't figure out how add SVG files to it and examples are lacking.
Let me be a little more specific with what I'm looking for. Let's say I have a SVG file that draws a box. When I mouse over that box I want to color to change triggered off a hover event. Do I have to edit the file and redraw the image? Feels like there should be a way of doing interactive SVG files with Qt.
I had the same problem and your question pointed me in right direction (using QGraphicsWebView()).
Solution is actually very simple:
import sys
from PyQt4 import QtCore, QtGui, QtSvg
from PyQt4.QtWebKit import QGraphicsWebView
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
scene = QtGui.QGraphicsScene()
view = QtGui.QGraphicsView(scene)
br = QtSvg.QGraphicsSvgItem("C:\your_interactive_svg.svg").boundingRect()
webview = QGraphicsWebView()
webview.load(QtCore.QUrl("C:\your_interactive_svg.svg"))
webview.setFlags(QtGui.QGraphicsItem.ItemClipsToShape)
webview.setCacheMode(QtGui.QGraphicsItem.NoCache)
webview.resize(br.width(), br.height())
scene.addItem(webview)
view.resize(br.width()+10, br.height()+10)
view.show()
sys.exit(app.exec_())
It works perfect for me (scripting and other stuff).
As you can see, I've also loaded my svg as QGraphicsSvgItem, because I didn't know other way to get size of my svg.
I figured out a way, but I don't think it's the best way. I have two files:
white.svg
green.svg
in the hover functions I render the image and force show it.
def hoverEnterEvent(self, event):
self.render.load('green.svg')
self.show()
def hoverLeaveEvent(self, event):
self.render.load('white.svg')
self.show()
where self is a QGraphicsSvgItem
I don't like this way because I now have to have two .svg files insted of one. If anyone has a better solution, I'm open to suggestions.

Take screenshot of multi-monitor setup

I'm taking a screenshot using this line
screen = QPixmap.grabWindow(QApplication.desktop().winId())
but apparently that doesn't grab the full desktop if the user has several monitors.
Is there a way to grab the desktop of all monitors into a single image?
According to this blog, just add the x, y, width, and height to grab the full desktop.
Just need to loop over QApplication.screens() and grab them one at a time like so...
Note: using Python 3.8 and PyQt5
import os
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
for screen in QApplication.screens():
screen_path = os.path.expanduser(f"~/Desktop/{screen.name()}.jpg")
screen.grabWindow(0).save(screen_path, 'jpg')
# grabWindow(0) means full screen
# for area use following format; x=0, y=0, w=-1, h=-1

Categories

Resources