Création de widgets "custom" avec QtDesigner et Qt5
Salut,
je me permets de relancer le sujet, j'ai voulu créer un widget perso en qt5 mais je n'ai pas retrouvé mon widget dans qt designer.
Fichier customwidgets/widgets/monlineeditwidget.py
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #! /usr/bin/python3
# -*- coding: utf-8 -*-
# Python v3
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MonLineEditWidget(QLineEdit):
#========================================================================
def __init__(self, parent=None):
super(MonLineEditWidget, self).__init__(parent)
# mettre un fond de couleur jaune à la ligne de saisie
self.setStyleSheet("background-color: yellow;") |
Fichier customwidgets/plugins/monlineeditplugin.py
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #! /usr/bin/python3
# -*- coding: utf-8 -*-
# Python v3
from PyQt5.QtGui import *
from PyQt5.QtDesigner import *
# ===== à adapter selon le widget! ==========================================
# nom (str) du fichier du widget sans extension
FICHIERWIDGET = "monlineeditwidget"
# nom (str) de la classe du widget importé
NOMCLASSEWIDGET = "MonLineEditWidget"
# nom (str) de l'instance crée dans Designer
NOMWIDGET = "monLineEditWidget"
# groupe (str) de widgets pour Designer
GROUPEWIDGET = "Mes widgets perso"
# texte (str) pour le toolTip dans Designer
TEXTETOOLTIP = "Un QLineEdit avec un fond jaune"
# texte (str) pour le whatsThis dans Designer
TEXTEWHATSTHIS = "Un QLineEdit avec un fond jaune"
# icone (rien ou QPixmap) pour présenter le widget dans Designer
ICONEWIDGET = QIcon() # sans pixmap, l'icone par défaut est celui de Qt
# ===========================================================================
# importation de la classe du widget
modulewidget = __import__(FICHIERWIDGET, fromlist=[NOMCLASSEWIDGET])
CLASSEWIDGET = getattr(modulewidget, NOMCLASSEWIDGET)
#############################################################################
class GeoLocationPlugin(QPyDesignerCustomWidgetPlugin):
"""classe pour renseigner Designer sur le widget
nom de classe à renommer selon le widget
"""
#========================================================================
def __init__(self, parent=None):
super(GeoLocationPlugin, self).__init__(parent)
self.initialized = False
#========================================================================
def initialize(self, core):
if self.initialized:
return
self.initialized = True
#========================================================================
def isInitialized(self):
return self.initialized
#========================================================================
def createWidget(self, parent):
"""retourne une instance de la classe qui définit le nouveau widget
"""
return CLASSEWIDGET(parent)
#========================================================================
def name(self):
"""définit le nom du widget dans QtDesigner
"""
return NOMCLASSEWIDGET
#========================================================================
def group(self):
"""définit le nom du groupe de widgets dans QtDesigner
"""
return GROUPEWIDGET
#========================================================================
def icon(self):
"""retourne l'icone qui represente le widget dans Designer
=> un QIcon() ou un QIcon(imagepixmap)
"""
return ICONEWIDGET
#========================================================================
def toolTip(self):
"""retourne une courte description du widget comme tooltip
"""
return TEXTETOOLTIP
#========================================================================
def whatsThis(self):
"""retourne une courte description du widget pour le "What's this?"
"""
return TEXTEWHATSTHIS
#========================================================================
def isContainer(self):
"""dit si le nouveau widget est un conteneur ou pas
"""
return False
#========================================================================
def domXml(self):
"""donne des propriétés du widget pour utilisation dans Designer
"""
return ('<widget class="{}" name="{}">\n' \
' <property name="toolTip" >\n' \
' <string>{}</string>\n' \
' </property>\n' \
' <property name="whatsThis" >\n' \
' <string>{}</string>\n' \
' </property>\n' \
'</widget>\n'\
).format(NOMCLASSEWIDGET, NOMWIDGET, TEXTETOOLTIP, TEXTEWHATSTHIS)
#========================================================================
def includeFile(self):
"""retourne le nom du fichier (str sans extension) du widget
"""
return FICHIERWIDGET |
Fichier designer.py
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #! /usr/bin/python3
# -*- coding: utf-8 -*-
# Python v3
import sys, os
from PyQt5.QtGui import *
from PyQt5.QtCore import *
# lance de la bibliothèque Qt4
app = QCoreApplication(sys.argv)
# trouve le répertoire d'exécution du présent programme
repbase = os.path.abspath(os.path.dirname(__file__))
# lit les variables d'environnement dans un dictionnaire
envdico = os.environ.copy()
env = QProcessEnvironment()
# enregistre dans PYTHONPATH le répertoire des fichiers des widgets
envdico['PYTHONPATH'] = os.path.join(repbase, 'customwidgets', 'widgets')
# enregistre dans PYQTDESIGNERPATH le répertoire des fichiers des plugins
envdico['PYQTDESIGNERPATH'] = os.path.join(repbase, 'customwidgets', 'plugins')
# crée la liste "nom=valeur" des variables d'environnement
for nom, valeur in envdico.items():
env.insert(nom, valeur)
# trouve l'adresse du Designer à lancer selon l'OS (corriger selon la configuration)
designer = QLibraryInfo.location(QLibraryInfo.BinariesPath)
if sys.platform == 'win32':
designer += r'\designer.exe' # Windows
elif sys.platform == 'linux':
designer += '/designer' # Linux
elif sys.platform == 'darwin':
designern += '/Designer.app/Contents/MacOS/Designer' # Mac OS X
else:
pass # autre cas à définir si nécessaire
# lance Designer dans un nouveau processus avec les variables d'environnement
proc = QProcess()
proc.setProcessEnvironment(env)
proc.start(designer)
proc.waitForFinished(-1)
sys.exit(proc.exitCode()) |
Une idée ? Bon week end à vous !