Résolu sur le forum : Borne Wallbox Pulsar Plus 7,4 kW sur abonnement 6 kVA : quel délestage avant accord copro (urgent)Ma panne diagnostiquée — réponse sous 48 h29 €

PyQt Lab’ : Graphiques Math : Pyqtgraph : Afficher un graphique Pyqtgraph vide avec des widgets de paramétrage.

Électroniquemis à jour le 24 avril 2023

PyQt Lab est un outil puissant qui permet aux utilisateurs de créer des graphiques mathématiques complexes et interactifs. Il est basé sur le framework PyQt et utilise le module Pyqtgraph pour afficher des graphiques. Dans cet article, nous allons vous montrer comment afficher un graphique Pyqtgraph vide avec des widgets de paramétrage. Nous verrons également comment ajuster les paramètres pour obtenir le graphique souhaité.

PyQt Lab’ : Graphiques Math : Pyqtgraph : Afficher un graphique Pyqtgraph vide avec des widgets de paramétrage.

Par X. HINAULT – Juin 2013

Ce que l’on va faire ici

  • Affichage d’un graphique pyqtgraph vide avec des widgets permettant de régler simplement les options d’affichage des axes.

Pré-requis

  • python 2.7
  • pyqt4.x
  • pyqtgraph

Le fichier d’interface *.ui

<?xml version=« 1.0 » encoding=« UTF-8 »?>
<ui version=« 4.0 »>
 <class>Form</class>
 <widget class=« QWidget » name=« Form »>
  <property name=« geometry »>
   <rect>
    <x>0</x>
    <y>0</y>
    <width>499</width>
    <height>416</height>
   </rect>
  </property>
  <property name=« windowTitle »>
   <string>PyQt + pyqtgraph : Graphique vide avec paramétrage axes</string>
  </property>
  <widget class=« PlotWidget » name=« graph »>
   <property name=« geometry »>
    <rect>
     <x>5</x>
     <y>10</y>
     <width>480</width>
     <height>360</height>
    </rect>
   </property>
  </widget>
  <widget class=« QPushButton » name=« pushButtonInit »>
   <property name=« geometry »>
    <rect>
     <x>10</x>
     <y>380</y>
     <width>85</width>
     <height>27</height>
    </rect>
   </property>
   <property name=« text »>
    <string>Initialiser</string>
   </property>
  </widget>
  <widget class=« QCheckBox » name=« checkBoxAxisBottom »>
   <property name=« geometry »>
    <rect>
     <x>100</x>
     <y>375</y>
     <width>82</width>
     <height>19</height>
    </rect>
   </property>
   <property name=« text »>
    <string>Axe X</string>
   </property>
   <property name=« checked »>
    <bool>true</bool>
   </property>
  </widget>
  <widget class=« QCheckBox » name=« checkBoxAxisLeft »>
   <property name=« geometry »>
    <rect>
     <x>200</x>
     <y>375</y>
     <width>82</width>
     <height>19</height>
    </rect>
   </property>
   <property name=« text »>
    <string>Axe Y</string>
   </property>
   <property name=« checked »>
    <bool>true</bool>
   </property>
  </widget>
  <widget class=« QCheckBox » name=« checkBoxLabelAxisLeft »>
   <property name=« geometry »>
    <rect>
     <x>200</x>
     <y>395</y>
     <width>96</width>
     <height>19</height>
    </rect>
   </property>
   <property name=« text »>
    <string>Label Axe Y</string>
   </property>
   <property name=« checked »>
    <bool>true</bool>
   </property>
  </widget>
  <widget class=« QCheckBox » name=« checkBoxLabelAxisBottom »>
   <property name=« geometry »>
    <rect>
     <x>100</x>
     <y>395</y>
     <width>96</width>
     <height>19</height>
    </rect>
   </property>
   <property name=« text »>
    <string>Label Axe X</string>
   </property>
   <property name=« checked »>
    <bool>true</bool>
   </property>
  </widget>
 </widget>
 <customwidgets>
  <customwidget>
   <class>PlotWidget</class>
   <extends>QGraphicsView</extends>
   <header>pyqtgraph</header>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>
 

Le fichier d’interface *.py

  • Fichier obtenu automatiquement avec l’utilitaire pyuic4 à partir du fichier *.ui créé avec QtDesigner :
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file ‘/home/xavier/www/mon_arduino/python_avec_arduino/mes_pyQt_tutos_v2/pyqtgraph/tuto_pyqt_pyqtgraph_graphique_vide_param/codes/tuto_pyqt_pyqtgraph_graphique_vide_param.ui’
#
# Created: Fri Jun  7 15:16:10 2013
#      by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8(« Form »))
        Form.resize(499, 416)
        self.graph = PlotWidget(Form)
        self.graph.setGeometry(QtCore.QRect(5, 10, 480, 360))
        self.graph.setObjectName(_fromUtf8(« graph »))
        self.pushButtonInit = QtGui.QPushButton(Form)
        self.pushButtonInit.setGeometry(QtCore.QRect(10, 380, 85, 27))
        self.pushButtonInit.setObjectName(_fromUtf8(« pushButtonInit »))
        self.checkBoxAxisBottom = QtGui.QCheckBox(Form)
        self.checkBoxAxisBottom.setGeometry(QtCore.QRect(100, 375, 82, 19))
        self.checkBoxAxisBottom.setChecked(True)
        self.checkBoxAxisBottom.setObjectName(_fromUtf8(« checkBoxAxisBottom »))
        self.checkBoxAxisLeft = QtGui.QCheckBox(Form)
        self.checkBoxAxisLeft.setGeometry(QtCore.QRect(200, 375, 82, 19))
        self.checkBoxAxisLeft.setChecked(True)
        self.checkBoxAxisLeft.setObjectName(_fromUtf8(« checkBoxAxisLeft »))
        self.checkBoxLabelAxisLeft = QtGui.QCheckBox(Form)
        self.checkBoxLabelAxisLeft.setGeometry(QtCore.QRect(200, 395, 96, 19))
        self.checkBoxLabelAxisLeft.setChecked(True)
        self.checkBoxLabelAxisLeft.setObjectName(_fromUtf8(« checkBoxLabelAxisLeft »))
        self.checkBoxLabelAxisBottom = QtGui.QCheckBox(Form)
        self.checkBoxLabelAxisBottom.setGeometry(QtCore.QRect(100, 395, 96, 19))
        self.checkBoxLabelAxisBottom.setChecked(True)
        self.checkBoxLabelAxisBottom.setObjectName(_fromUtf8(« checkBoxLabelAxisBottom »))

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtGui.QApplication.translate(« Form », « PyQt + pyqtgraph : Graphique vide avec paramétrage axes », None, QtGui.QApplication.UnicodeUTF8))
        self.pushButtonInit.setText(QtGui.QApplication.translate(« Form », « Initialiser », None, QtGui.QApplication.UnicodeUTF8))
        self.checkBoxAxisBottom.setText(QtGui.QApplication.translate(« Form », « Axe X », None, QtGui.QApplication.UnicodeUTF8))
        self.checkBoxAxisLeft.setText(QtGui.QApplication.translate(« Form », « Axe Y », None, QtGui.QApplication.UnicodeUTF8))
        self.checkBoxLabelAxisLeft.setText(QtGui.QApplication.translate(« Form », « Label Axe Y », None, QtGui.QApplication.UnicodeUTF8))
        self.checkBoxLabelAxisBottom.setText(QtGui.QApplication.translate(« Form », « Label Axe X », None, QtGui.QApplication.UnicodeUTF8))

from pyqtgraph import PlotWidget

if __name__ == « __main__ »:
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

 

Le fichier d’application *Main.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

# par X. HINAULT – Mai 2013 – Tous droits réservés
# GPLv3 – www.mon-club-elec.fr

# modules a importer
from PyQt4.QtGui import *
from PyQt4.QtCore import *  # inclut QTimer..
import os,sys

import pyqtgraph as pg # pour accès à certaines constantes pyqtgraph, widget, etc…

AvecPrincipes d’utilisation des alimentations avec une carte Arduino et des servomoteurs

import numpy as np # math et tableaux

from tuto_pyqt_pyqtgraph_graphique_vide_param import * # fichier obtenu à partir QtDesigner et pyuic4

# +/- variables et objets globaux

class myApp(QWidget, Ui_Form): # la classe reçoit le Qwidget principal ET la classe définie dans test.py obtenu avec pyuic4
        def __init__(self, parent=None):
                QWidget.__init__(self) # initialise le Qwidget principal
                self.setupUi(parent) # Obligatoire

                # — Variables de classe

                # — Paramétrage des widgets de l’interface GUI si nécessaire —

                # — Connexions entre signaux des widgets et fonctions
                # connecte chaque signal utilisé des objets à l’appel de la fonction voulue

                self.connect(self.pushButtonInit, SIGNAL(« clicked() »), self.pushButtonInitClicked)
                self.connect(self.checkBoxAxisBottom, SIGNAL(« clicked() »), self.checkBoxAxisBottomClicked) # connecte le signal Clicked de l’objet checkBox à l’appel de la fonction voulue
                self.connect(self.checkBoxAxisLeft, SIGNAL(« clicked() »), self.checkBoxAxisLeftClicked) # connecte le signal Clicked de l’objet checkBox à l’appel de la fonction voulue
                self.connect(self.checkBoxLabelAxisBottom, SIGNAL(« clicked() »), self.checkBoxLabelAxisBottomClicked) # connecte le signal Clicked de l’objet checkBox à l’appel de la fonction voulue
                self.connect(self.checkBoxLabelAxisLeft, SIGNAL(« clicked() »), self.checkBoxLabelAxisLeftClicked) # connecte le signal Clicked de l’objet checkBox à l’appel de la fonction voulue

                # — Code actif initial  —

                #– initialise le graphique pyqtgraph —
                # l’objet self.graph correspond au plotWidget créé dans QtDesigner

                # aspect fond /axes
                #self.graph.hideAxis(‘left’) # masque axes – ‘left’, ‘bottom’, ‘right’, or ‘top’               
                self.graph.setBackgroundBrush(QBrush(QColor(Qt.white))) # la classe PlotWidget est un GraphicsWidget qui est un QGraphics View
                self.graph.showGrid(x=True, y=True)  # affiche la grille
                self.graph.getAxis(‘bottom’).setPen(pg.mkPen(0,0,255)) # couleur de l’axe + grille
                self.graph.getAxis(‘left’).setPen(pg.mkPen(255,0,0)) # couleur de l’axe + grille

                # légende des axes
                labelStyle = {‘color’: ‘#00F’, ‘font-size’: ’10pt’} # propriétés CSS à utiliser pour le label
                self.graph.getAxis(‘bottom’).setLabel(‘X’, units=‘unit’, **labelStyle) # label de l’axe
                self.graph.getAxis(‘left’).setLabel(‘Y’, units=‘unit’, **labelStyle) # label de l’axe

                # adaptation échelle axes
                self.graph.enableAutoRange(axis=pg.ViewBox.YAxis, enable=False) # fonction plotItem : désactive autoscale Y
                self.graph.setYRange(10,10) # fonction plotItem : fixe échelle des Y

                # interactivité
                #self.graph.setInteractive(False) # fonction QGraphics View : pour inactiver interaction souris
                self.graph.getViewBox().setMouseMode(pg.ViewBox.RectMode)  # fonction ViewBox pas accessible depuis PlotWidget : fixe selection par zone
                self.graph.setMouseEnabled(x=False, y=True) # désactive interactivité axe X

        # — les fonctions appelées, utilisées par les signaux —

        # pushButton
        def pushButtonInitClicked(self):
                print(« Bouton Init cliqué »)
                self.graph.setYRange(10,10) # fonction plotItem : fixe échelle des Y
                self.graph.setXRange(0,1) # fonction plotItem : fixe échelle des Y

        def checkBoxAxisBottomClicked(self):
                print(« Checkbox axe X cliqué »)

                if self.checkBoxAxisBottom.isChecked(): # si checkBox sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxAxisBottom.isChecked()))
                        self.graph.showAxis(‘bottom’)
                        # self.graph.showAxis(‘bottom’, True) # équivalent
                        if self.checkBoxLabelAxisBottom.isChecked(): self.graph.showLabel(‘bottom’,True)        
                else : # si checkBox pas sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxAxisBottom.isChecked()))
                        self.graph.hideAxis(‘bottom’)
                        # self.graph.showAxis(‘bottom’, False) # équivalent
                        self.graph.showLabel(‘bottom’,False)

        def checkBoxAxisLeftClicked(self):
                print(« Checkbox axe Y cliqué »)

DesAteliers Arduino : des supports PDF didactiques pour apprendre et approfondir Arduino pas à pas !

                if self.checkBoxAxisLeft.isChecked(): # si checkBox sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxAxisLeft.isChecked()))
                        self.graph.showAxis(‘left’)
                        # self.graph.showAxis(‘left’, True) # équivalent
                        if self.checkBoxLabelAxisLeft.isChecked():self.graph.showLabel(‘left’,True)                    
                else : # si checkBox pas sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxAxisLeft.isChecked()))
                        self.graph.hideAxis(‘left’)
                        self.graph.showLabel(‘left’,False)

        def checkBoxLabelAxisBottomClicked(self):
                print(« Checkbox Label axe X cliqué »)

                if self.checkBoxLabelAxisBottom.isChecked(): # si checkBox sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxLabelAxisBottom.isChecked()))
                        self.graph.showLabel(‘bottom’,True)    
                else : # si checkBox pas sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxLabelAxisBottom.isChecked()))
                        self.graph.showLabel(‘bottom’,False)

        def checkBoxLabelAxisLeftClicked(self):
                print(« Checkbox Label axe Y cliqué »)

                if self.checkBoxLabelAxisLeft.isChecked(): # si checkBox sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxLabelAxisLeft.isChecked()))
                        self.graph.showLabel(‘left’,True)                      
                else : # si checkBox pas sélectionné
                        print(« Etat checkBox = «  + str(self.checkBoxLabelAxisLeft.isChecked()))
                        self.graph.showLabel(‘left’,False)

        # — fonctions de classes autres—    

# — Autres Classes utiles —

# — Classe principale (lancement)  —
def main(args):
        a=QApplication(args) # crée l’objet application
        f=QWidget() # crée le QWidget racine
        c=myApp(f) # appelle la classe contenant le code de l’application
        f.show() # affiche la fenêtre QWidget
        r=a.exec_() # lance l’exécution de l’application
        return r

if __name__==« __main__ »: # pour rendre le code exécutable
        main(sys.argv) # appelle la fonction main

 

Utilisation

  • Les 2 fichiers suivants sont à enregistrer dans un même répertoire, l’un en nom.py et l’autre en nomMain.py.
  • Puis lancer l’application depuis Geany ou équivalent, en exécutant le fichier nomMain.py
  • La molette de souris assure le zoom

Donnez votre avis

Soyez le 1er à noter cet article
ou bien laissez un avis détaillé


Partagez cet article maintenant !


Ça ne règle pas votre cas ?

Décrivez la panne sur le forum, avec une photo si vous pouvez : les membres qui ont eu la même répondent, et le sujet reste pour les suivants.

Avatar photoAvatar photoAvatar photoAvatar photoAvatar photoRejoindre les 54 membres — gratuit, 44 pannes résolues

Dans le même tiroir

Reconnaissance vocale avec Processing
Électronique

Reconnaissance vocale avec Processing

La reconnaissance vocale est un domaine en pleine expansion qui offre de nombreuses possibilités pour les développeurs. Avec Processing, un…

Portrait de Inès DameronInès Dameron · 22 Avr 2023
Mon Club Elec
Électronique

Programmer le pcDuino : Python simple : …

Le pcDuino est un système informatique open source qui offre aux développeurs une plateforme puissante et flexible pour créer des…

Portrait de Inès DameronInès Dameron · 23 Avr 2023

Réagissez à cet article

La lettre du club

Une lettre par mois, accrochée au panneau

Les sujets du forum résolus dans le mois, un guide, un chiffre qu’on peut vérifier chez soi. Rien d’autre, jamais plus souvent — et on se désabonne d’un clic.

Ce qu’il y a dedans

Votre adresse

Une lettre par mois. Désabonnement en un clic.

Partagez votre réaction