IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

PyQt Python Discussion :

Comment mettre à jour une QGraphicsView ?


Sujet :

PyQt Python

  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Décembre 2011
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2011
    Messages : 5
    Points : 4
    Points
    4
    Par défaut Comment mettre à jour une QGraphicsView ?
    Bonjour, je suis actuellement en train de coder un automate cellulaire (style jeux de la vie) et je n'arrive pas à faire s'actualiser l'affichage de mon programme. Actuellement je paint des PixmapObjects sur une QgraphicsScene qui sont affichés par une QGraphicView. Seul problème: La QgraphicView ne prend en compte que la première génération et elle ne s'affiche qu'à la fin des calculs.

    Je précise que je suis débutant en programmation objet et en interface graphique.

    Voici mon code: (j'ai fais quelques coupures pour plus de lisibilité)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
     
    import sys
    import random
    from PySide.QtCore import *
    from PySide.QtGui import *
     
    class Pixmap(QGraphicsObject):
        def __init__(self, pix):
            super(Pixmap, self).__init__()
            self.p = QPixmap(pix)
     
        def paint(self, painter, option, widget):
            painter.drawPixmap(QPointF(), self.p)
     
        def boundingRect(self):
            return QRectF(QPointF(0, 0), QSizeF(self.p.size()))
     
    def affichage(N,tableau,scene):
        for i in range(N):
            for j in range(N):
                if tableau[i][j][0] == "B" or tableau[i][j][0] == "TB":
                    brindille = Pixmap(QPixmap('./Images/branche.gif'))
                    brindille.setPos(i*35,j*35)
                    scene.addItem(brindille)
                elif tableau[i][j][0] == "T" or tableau[i][j][0] == "TB":
                    if tableau[i][j][1] == "H":
                        termite = Pixmap(QPixmap('./Images/termiteH.gif'))
                    elif tableau[i][j][1] == "B":
                        termite = Pixmap(QPixmap('./Images/termiteB.gif'))
                    elif tableau[i][j][1] == "D":
                        termite = Pixmap(QPixmap('./Images/termiteD.gif'))
                    elif tableau[i][j][1] == "G":
                        termite = Pixmap(QPixmap('./Images/termiteG.gif'))
                    termite.setPos(i*35,j*35)
                    scene.addItem(termite)
        return scene
     
    class Termite:
        def __init__(self):
            self.timer = QTimeLine(1000)
            self.timer.setFrameRange(0, 100)
            self.timer.start()
            self.N = 15
            self.B = 25
            self.T = 30
            self.tableau = []
            creation(self.N,self.tableau)
            remplissage(self.N,self.B,self.T,self.tableau)
     
            self.scene = QGraphicsScene(0,0,self.N*35,self.N*35)
            self.scene = affichage(self.N,self.tableau,self.scene)
            self.view = QGraphicsView(self.scene)
     
    def main():
     
        app = QApplication(sys.argv)
        t = Termite()
        t.view.show()
        for i in range(100):
            tableau = generation(t.N,t.tableau) #fonction qui renvoie la nouvelle génération de termites
            scene = affichage(t.N,t.tableau,t.scene)
            t.view.update()
     
        sys.exit(app.exec_())
     
    if __name__ == '__main__':
        main()
    Pour ceux qui voudraient faire tourner le programme voilà le code complet:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
     
    import sys
    import random
    import time
    from PySide.QtCore import *
    from PySide.QtGui import *
     
    class Pixmap(QGraphicsObject):
        def __init__(self, pix):
            super(Pixmap, self).__init__()
            self.p = QPixmap(pix)
     
        def paint(self, painter, option, widget):
            painter.drawPixmap(QPointF(), self.p)
     
        def boundingRect(self):
            return QRectF(QPointF(0, 0), QSizeF(self.p.size()))
     
     
    class Options(QDialog):
     
        def __init__(self, parent=None):
            super(Options, self).__init__(parent)
            self.setWindowTitle("Options")
            # Create widgets
            self.N = QLineEdit("Entrer un entier N (taille du monde = N x N)")
            self.B = QLineEdit("    Entrer le nombre de brindilles a placer     ")
            self.T = QLineEdit("     Entrer le nombre de termites a placer      ")
            self.buttonOk = QPushButton("Ok")
            self.buttonOut = QPushButton("Exit")
            self.resize(320,150)
            # Create layout and add widgets
            layout = QVBoxLayout()
            layout.addWidget(self.N)
            layout.addWidget(self.B)
            layout.addWidget(self.T)
            layout.addWidget(self.buttonOk)
            layout.addWidget(self.buttonOut)
            # Set dialog layout
            self.setLayout(layout)
            # Add button signal to greetings slot
            self.buttonOk.clicked.connect(self.Go)
            self.buttonOut.clicked.connect(exit)
     
    def creation(N,tableau):
        for i in range(N):
            tableau.append([[0,0]]*N)
     
    def remplissage(N,B,T,tableau):
        orientation = ["H","B","D","G"]
        proportionB = float(B)/(N*N)
        proportionT = float(T)/(N*N)
        print proportionB
        print proportionT
        if proportionB+proportionT > 1:
            return "Trop de termites ou de brindilles"
        for i in range(N):
            for j in range(N):
                nbRand = random.random()
                if nbRand < proportionB:
                    tableau[i][j] = ["B",0]
                elif nbRand < proportionB + proportionT:
                    tableau[i][j] = ["T",random.choice(orientation)]
        print tableau
     
    def voisin(tableau,i,j):
        voisins = []
        voisins.append(tableau[i-1][j-1])
        voisins.append(tableau[i+1][j-1])
        voisins.append(tableau[i-1][j])
        voisins.append(tableau[i+1][j])
        return voisins
     
    def deplacement(direction,N,tableau,nextGen,i,j,type):
        if direction == "H":
            if j-1 >= 0:        
                i1,j1 = i,j-1
            else:
                i1,j1 = i,N-1
            oppose = "B"
        elif direction == "B":
            if j+1 < N:
                i1,j1 = i,j+1
            else:
                i1,j1 = i,0
            oppose = "H"
        elif direction == "D":
            if i+1 < N:
                i1,j1 = i+1,j
            else:
                i1,j1 = 0,j
            oppose = "G"
        else:
            if i-1 >= 0:
                i1,j1 = i-1,j
            else:
                i1,j1 = N-1,j
            oppose = "D"
     
        if nextGen[i1][j1][0] == 0 and tableau[i1][j1][0] == 0:
            nextGen[i1][j1] = [type,direction]
        elif nextGen[i1][j1][0] == "B" and tableau[i1][j1][0] == "B" and tableau[i][j][0] != "TB":
            nextGen[i][j] = ["TB",direction]
            nextGen[i1][j1][0] = 0
        elif tableau[i][j] == "TB" and nextGen[i1][j1] == "B" and tableau[i1][j1] == "B":
            voisins = voisin(tableau,i,j)
            for case in voisins:
                if case[0] == 0:
                    case[0] = "B"
                    break
            nextGen[i][j][0] = "T"
        else:
            nextGen[i][j] = [type,oppose]
     
    def nbTermites(tableau): #Compte le nb de termites
        nb = 0
        nbB = 0
        for i in range(len(tableau)):
            for j in range(len(tableau)):
                if tableau[i][j][0] == "T" or tableau[i][j][0] == "TB":
                    nb += 1
                if tableau[i][j][0] == "B" or tableau[i][j][0] == "TB":
                    nbB += 1
        print nb
        print nbB
     
    def generation(N,tableau):
        nextGen = []
        for i in range(N):
            nextGen.append([[0,0]]*N)
        for i in range(N):
            for j in range(N):
                case = tableau[i][j]
                if case[0] == "B":
                    nextGen[i][j] = ["B",0]
                if case[0] == "T" or case[0] == "TB":
                    nbRand = random.random()
                    if (case[1] == "H" and nbRand < 0.8) or (0.8 <= nbRand < 0.9 and case[1] == "G") or (nbRand >= 0.9 and case[1] == "D"):
                        deplacement("H",N,tableau,nextGen,i,j,case[0])
                    elif (case[1] == "B" and nbRand < 0.8) or (0.8 <= nbRand < 0.9 and case[1] == "D") or (nbRand >= 0.9 and case[1] == "G"):
                        deplacement("B",N,tableau,nextGen,i,j,case[0])
                    elif (case[1] == "D" and nbRand < 0.8) or (0.8 <= nbRand < 0.9 and case[1] == "H") or (nbRand >= 0.9 and case[1] == "B"):
                        deplacement("D",N,tableau,nextGen,i,j,case[0])
                    else: #(case[1] == "G" and nbRand < 0.8) or (0.8 <= nbRand < 0.9 and case[1] == "B") or (nbRand >= 0.9 and case[1] == "H"):
                        deplacement("G",N,tableau,nextGen,i,j,case[0])
        print "NextGen:"
        print nextGen
        print "nb termites tableau"
        nbTermites(tableau)
        print "nb termites nextGen"
        nbTermites(nextGen)
        return nextGen
     
    def affichage(N,tableau,scene):
        for i in range(N):
            for j in range(N):
                if tableau[i][j][0] == "B" or tableau[i][j][0] == "TB":
                    brindille = Pixmap(QPixmap('./Images/branche.gif'))
                    brindille.setPos(i*35,j*35)
                    scene.addItem(brindille)
                elif tableau[i][j][0] == "T" or tableau[i][j][0] == "TB":
                    if tableau[i][j][1] == "H":
                        termite = Pixmap(QPixmap('./Images/termiteH.gif'))
                    elif tableau[i][j][1] == "B":
                        termite = Pixmap(QPixmap('./Images/termiteB.gif'))
                    elif tableau[i][j][1] == "D":
                        termite = Pixmap(QPixmap('./Images/termiteD.gif'))
                    elif tableau[i][j][1] == "G":
                        termite = Pixmap(QPixmap('./Images/termiteG.gif'))
                    termite.setPos(i*35,j*35)
                    scene.addItem(termite)
        return scene
     
    class Termite:
        def __init__(self):
            self.timer = QTimeLine(1000)
            self.timer.setFrameRange(0, 100)
            self.timer.start()
            self.N = 15
            self.B = 25
            self.T = 30
            self.tableau = []
            creation(self.N,self.tableau)
            remplissage(self.N,self.B,self.T,self.tableau)
     
            self.scene = QGraphicsScene(0,0,self.N*35,self.N*35)
            self.scene = affichage(self.N,self.tableau,self.scene)
            self.view = QGraphicsView(self.scene)
     
    def main():
     
        app = QApplication(sys.argv)
        t = Termite()
        t.view.show()
        for i in range(10): #Pour l'instant le programme ne calcule que 10 générations
            tableau = generation(t.N,t.tableau) #fonction qui renvoie la nouvelle génération de termites
            scene = affichage(t.N,t.tableau,t.scene)
            t.view.update()
        sys.exit(app.exec_())
     
    if __name__ == '__main__':
        main()
    Merci d'avance à tous ceux qui auront une solution ou une piste à me proposer. Ou même tout simplement à ceux qui auront des conseils sur comment organiser mon interface graphique.

    Cordialement,

    Gorglum

  2. #2
    Expert éminent

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 300
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 300
    Points : 6 780
    Points
    6 780
    Par défaut
    Salut,

    update() est généralement sans effets.
    Il est préferable d'utiliser QtCore.QCoreApplication.processEvents()

    Si je fais ceci dans ton code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    def main():
     
        app = QApplication(sys.argv)
        t = Termite()
        t.view.show()
        QCoreApplication.processEvents()
        for i in range(10): #Pour l'instant le programme ne calcule que 10 générations
            tableau = generation(t.N,t.tableau) #fonction qui renvoie la nouvelle génération de termites
            scene = affichage(t.N,t.tableau,t.scene)
            QCoreApplication.processEvents()
            print i
            time.sleep(0.2)
        sys.exit(app.exec_())
    je vois la première disposition des objets, mais manifestement les changements ne sont pas appliqués.

    C'est normal que ton tableau soit à trois dimensions ? j'ai un peu de mal à suivre le fil du code j'avoue.

    Personnellement, j'aurais fait des brindilles et des termites des instances de QGraphicsPixmapItem dont la position, le status vie/mort est aurait été des arguments, ne fut-ce que pour simplifier la lecture.

    Une chose que j'ai remarqué

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    ...
    termite = Pixmap(QPixmap('blue_ball_20.png'))
     
    ...
    self.p = QPixmap(pix)
    Une QPixmap de QPixmap ce n'est pas nécessaire, il ne faut pas oublier que Qt ne te dira pas forcément que l'objet est 'null' en cas d'erreur de création d'une QImage ou QPixmap, il n'affiche rien sans plus.

  3. #3
    Candidat au Club
    Profil pro
    Inscrit en
    Décembre 2011
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2011
    Messages : 5
    Points : 4
    Points
    4
    Par défaut
    Ça a l'air de marcher nikel ! J'arrive enfin à faire évoluer l'affichage !!!

    Merci beaucoup, j'étais bloqué sur ce problème depuis 3 jours et je n'avais vu nul part cette fonction de QCoreApplication.ProcessEvents().

    Je posterai mon code ici dès que j'aurai fini mon programme, j'en profiterai aussi pour mettre quelques commentaires et expliquer le pourquoi du comment de mes décisions (pour le moment je suis pressé de faire fonctionner ça correctement). Encore merci !

Discussions similaires

  1. Comment mettre à jour une page jsp chaque seconde
    Par zizoux5 dans le forum Struts 1
    Réponses: 6
    Dernier message: 25/05/2007, 18h37
  2. Réponses: 14
    Dernier message: 26/03/2007, 16h52
  3. Réponses: 1
    Dernier message: 15/09/2006, 11h24
  4. Comment mettre à jour une date ?
    Par Hokagge dans le forum MFC
    Réponses: 6
    Dernier message: 22/03/2006, 12h30
  5. Comment mettre à jour une ligne sans doublon via déclencheur
    Par fuelcontact dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 02/08/2004, 15h56

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo