PyQtgraph - Graphing with a Ui File
08/12/2023, Sat
Tags:
#cli-tools
PyQtgraph Graph in Native Window
Dedicating a UI file to store the application layout will make for a more organized process when working with PyQt. The Python code will be cleaner if it focuses on creating the dynamic data that will be inserted into the ui file.
To demonstrate this, create a window.ui
file.
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
</layout>
</widget>
</widget>
</ui>
Now create a main.py
file loading the graphing dependencies and window.ui
file.
from PyQt6 import QtWidgets, uic
from PyQt6.QtWidgets import QMainWindow
import pyqtgraph as pg
class Main(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# Load the UI file and make a variable reference
# for later graph placement
self.ui = uic.loadUi("window.ui", self)
Create the PyQtgraph plot area and graph.
from PyQt6 import QtWidgets, uic
from PyQt6.QtWidgets import QMainWindow
import pyqtgraph as pg
class Main(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# Load the UI file and make a variable reference
# for later graph placement
self.ui = uic.loadUi("window.ui", self)
# Create the pyqtgraph plot area
# Bar Graph Configuration: https://pyqtgraph.readthedocs.io/en/latest/api_reference/graphicsItems/bargraphitem.html
plot = pg.PlotWidget()
x1 = [5, 4, 3, 2, 1]
y = [1, 2, 3, 4, 5]
# Create the bar graph
bargraph = pg.BarGraphItem(x0=0, y=y,width=x1, height=0.7)
# Place the bar graph into the plot area
plot.addItem(bargraph)
Finally, reference the widget layout in the UI file and insert the PyQtgraph plot area into the layout.
from PyQt6 import QtWidgets, uic
from PyQt6.QtWidgets import QMainWindow
import pyqtgraph as pg
class Main(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# Load the UI file and make a variable reference
# for later graph placement
self.ui = uic.loadUi("window.ui", self)
# Create the pyqtgraph plot area
plot = pg.PlotWidget()
x1 = [5, 4, 3, 2, 1]
y = [1, 2, 3, 4, 5]
# Create the bar graph
bargraph = pg.BarGraphItem(x0=0, y=y,width=x1, height=0.7)
# Place the bar graph into the plot area
plot.addItem(bargraph)
# Programmatic insertion of graph into native window
self.ui.verticalLayout.addWidget(plot)
def main():
app = QtWidgets.QApplication([])
win = Main()
win.show()
app.exec()
if __name__ == '__main__':
main()
exit()