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 :

Gomme et QImage [QtGui]


Sujet :

PyQt Python

  1. #1
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Gomme et QImage
    Bonjour à tous, suite à ma discussion (cf.lien
    http://www.developpez.net/forums/d12...e/#post6726180 )

    J'aimerais pouvoir implémenter une gomme qui effacerait les "imperfections " d'une QImage, je vais me pencher plus sérieusement sur la questions.
    Merci d'avance pour votre aide ^^.

  2. #2
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Première idée
    Après réflexion, je pense qu'une solution serait d'avoir un "Pen" qui soit de la même couleur que le fond de l'image ou la couleur sélectionnée et qui effacerai
    les imperfections.

    Ce qui me manque, c'est qu'il faut surcharger paintEvent j'imagine ? Il est possible que d'avoir une seule méthode paintEvent ?
    Rajouter une sorte de "pen" je sais qu'on peut mettre une image dans le brush, j'aimerais récupérer la couleur du pixel que je sélectionne pour la mettre dedans, je ne sais pas si c'est possible ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
      def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            self.pen = QPen()
            self.pen.setWidth(3);
            self.pen.setBrush(green);
            painter.setPen(self.pen);
    Merci de vos conseils.

  3. #3
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Pas besoin de surcharger à nouveau paintEvent, définit une variable du genre 'mode' pour savoir si on doit sélectionner ou bien gommer, puis utilise cette variable dans le mouseEnterEvent et mouseMoveEvent pour dessiner la couleur de ton choix à l'emplacement désiré (contenu dans l'évènement).

  4. #4
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Précision
    Selon toi , je devrais donc utiliser cette variable avec une sorte de if en gros si jamais le mode gomme est on, j'active la fonction avec la couleur choisie sinon je sélectionne.
    ça me parait pas mal, je vais travailler ça.

  5. #5
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Premier Essai
    J'ai réussi sur un de mes test à dessiner mes traits comme je voulais. Cependant dans mon projet réel , j'ai du mal à permettre l'activation du dessin.
    De plus, j'aimerais un cercle plein et j'ai du mal à voir comment le faire en python :s
    Voici mon code :
    Merci encore et bon week end^^
    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
    from PySide.QtGui import QApplication, QWidget, QPainter, QKeySequence,QColor
    from PySide.QtGui import QImage, QRubberBand, QMainWindow, QAction, QMenuBar, QFileDialog, QScrollArea
    from PySide.QtCore import QSize, QRect,QRectF
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
     
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            _action = QAction("Rubber On",_edit)
            _action.triggered.connect(self.__actionRubber)
            _edit.addAction(_action)
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
        def __actionRubber(self):
            self.__mode = "rub"
     
     
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
            #Init of the boolean to know whether we select or rub
            self.__mode = "rub"
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
            self.__rub= QRectF(10.0, 20.0, 80.0, 60.0)
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self.__mode =="select":
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self.__mode =="rub":
                self.paintEvent(e)
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            if self.__mode=="rub":
                painter.drawLine(100,200,100,200)
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  6. #6
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Ne dessine pas la ligne dans le paintEvent, créé un QPainter sur ta QImage interne et dessine dessus.

    Selon le mode, tu récupère les coordonnées d'origine lors d'un mousePressEvent et tu dessine ta ligne lors du mouseReleaseEvent.

    EDIT: pour voir ta ligne se dessiner (pour savoir où relâcher la souris comme dans tout logiciel de dessin), dessine la aussi avec le QPainter du paintEvent juste après le drawImage.

    Pour le cercle, voir la méthode drawArc de QPainter.

  7. #7
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut
    Je teste ça et je poste demain la réponse une fois que j'ai bien bosser .
    Bonne soirée.

  8. #8
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Deuxieme essai
    Je suis pas certains d'avoir compris ce que tu voulais par dessiner sur la QImage interne, est- ce que cela voulait dire exécuter l'action dans la MainWindows ?

    Sinon pour le drawArc, je ne sais pas si c'est la meilleure solution en tout cas je me souviens avoir fais à peu près la même chose en java et j'utilisais une line enfin une freehandLine pour pouvoir dessiner plutôt gommer ou je voulais.
    En tout cas, voila ce que j'ai fais pour essayer de le mettre en appli :
    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
     
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
     
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            _action = QAction("Rubber On",_edit)
            _action.triggered.connect(self.__actionRubber)
            _edit.addAction(_action)
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
        def __actionRubber(self):
            self.__mode = "rub"
            painter = QPainter(self)
            painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
     
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
            #Init of the boolean to know whether we select or rub
            self.__mode = "rub"
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
       def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self.__mode =="select":
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self.__mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
     
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self.__mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
     
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  9. #9
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Je mettrai plus la ligne 64 à la place de la ligne 110 en termes de logique, puisque le widget affichant l'image est l'ImageView et non la MainWindow.

    Pour la QImage interne, je parlai évidemment de __image dans l'ImageView puisque le QPainter peut s'initialiser sur celle-ci au lieu d'un widget.

    Enfin, pour drawArc, cela permet de dessiner des arcs de cercle, donc des cercles entiers avec les bonnes valeurs pour les angles.

  10. #10
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut
    Oui, c'est vrai.
    C'est afficher par ImageView je vais modifier cela en espérant que ça marche ^^.
    Pour l'arc, je vais faire des essais une fois que j'arriverais à dessiner les lignes déjà.
    Bon dimanche.

  11. #11
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Problème de redéfinition du painter
    J'ai remplacé la ligne 68 mais j'ai un problème de redéfinition du painter, peut-être redéfinir le mode, je n'ai pas l'impression qu'il prenne vraiment la condition.
    Merci de l'aide ^^.
    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
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
     
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            _action = QAction("Rubber On",_edit)
            _action.triggered.connect(self.__actionRubber)
            _edit.addAction(_action)
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
        def __actionRubber(self):
            self.__mode = "rub"
            painter = QPainter(self)
     
     
     
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
            #Init of the boolean to know whether we select or rub
            self.__mode = "rub"
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
            self.__rub= QRectF(10.0, 20.0, 80.0, 60.0)
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self.__mode =="select":
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self.__mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
     
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self.__mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  12. #12
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Je n'ai pas trop compris ta phrase mais il me semble en regardant ton code que tu ne change pas le __mode de ton ImageView, uniquement le __mode de ta MainWindow, ce qui pourrait expliquer un problème de changement de mode.

  13. #13
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Problème d'accès au mode
    J'ai modifié l'accès à la variable, il suffira de cliquer sur une checkbox pour changer de mode ensuite je ne vois pas comment accéder au mode dans l'image view pour lancer le paintEvent
    Merci ^^.
    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
     
    from PySide.QtGui import QApplication, QWidget, QPainter, QKeySequence,QColor,QCheckBox,QStatusBar
    from PySide.QtGui import QImage, QRubberBand, QMainWindow, QAction, QMenuBar, QFileDialog, QScrollArea
    from PySide.QtCore import QSize, QRect,QRectF,Qt
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
     
            statusbar = QStatusBar(self)
            self.setStatusBar(statusbar)
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            #Check Box rub
            self._ckbox = QCheckBox("Rubber On")
            statusbar.addWidget(self._ckbox)
            if self._ckbox.isChecked():
                self._mode = "rub"
            else :
                self._mode = "select"
            #Init of the boolean to know whether we select or rub
            self.image._setMode(self._mode)
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
     
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
            self._mode = "rub"
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
     
        def _getMode(self):
            return self._mode
        def _setMode(self,_newMode):
            self._mode= _newMode
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self.__mode =="select":
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
     
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self.__mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  14. #14
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Le fait d'avoir un double '__' devant une variable la rend 'privée' (c'est plus dur mais pas impossible d'y accéder de l’extérieur). Soit tu enlève ces '__' soit tu créé une méthode d'accès dans la classe ImageView du genre setMode(mode) qui te permet de le changer.

  15. #15
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Suppresion var privé Mode et ajout propriété pour get/set
    J'ai rajouté une propriété pour définir les getter/setters malgré tout il ne reconnait pas le mode malheureusement ;s
    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
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
     
            statusbar = QStatusBar(self)
            self.setStatusBar(statusbar)
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            #Check Box rub
            self._ckbox = QCheckBox("Rubber On")
            statusbar.addWidget(self._ckbox)
            if self._ckbox.isChecked():
                self._mode = "rub"
            else :
                self._mode = "select"
            #Init of the boolean to know whether we select or rub
            self.image._setMode(self._mode)
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
     
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
            #Get of the mode
            self._mode = image.mode
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
     
            #Init of the property for mode
            mode = property(self._getMode,self._setMode)
     
        def _getMode(self):
            return self._mode
        def _setMode(self,_newMode):
            self._mode= _newMode
     
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self._mode =="select":
                #__ private variable 
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
     
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  16. #16
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Dans le setMode du ImageView, essaie d'ajouter un self.update() juste après le self._mode = _newMode

  17. #17
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Ajout du update() mais Prob avec l'attribut mode
    J'ai rajouté le update() qui devrait rafraichir la vue malgré tout il ne reconnait toujours pas l'attribut mode.
    Je ne sais pas si j'utilise bien la property pour avoir les bon get/set activés car j'aimerais avoir une réactivité lors du changement de mode .

    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
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
            statusbar = QStatusBar(self)
            self.setStatusBar(statusbar)
     
     
            """
            Adding of actions for the tool bar
            """
            iconToolBar = self.addToolBar("iconBar")
     
            #About 
            _actionAbout = QAction(self)
            _actionAbout.triggered.connect(self._actionAbout)
     
            _actionAbout.setIcon(QIcon("Pics\info-icon.jpg"))
            _actionAbout.setStatusTip("Pop up the About dialog.")
            iconToolBar.addAction(_actionAbout)
            #Rubber
            _actionRubber = QAction(self)
     
            _actionRubber.setIcon(QIcon("Pics\eraser2.png"))
            _actionRubber.setStatusTip("Enable or Disable eraser tool")
            iconToolBar.addAction(_actionRubber)
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            #Check Box rub
            self._ckbox = QCheckBox("Rubber On")
            statusbar.addWidget(self._ckbox)
            if self._ckbox.isChecked():
                self._mode = "rub"
            else :
                self._mode = "select"
            #Init of the boolean to know whether we select or rub
            self.image._setMode(self._mode)
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
        def _actionAbout(self):
            '''Popup a box with about message.'''
            QMessageBox.about(self, "About PySide, Platform and the like",
            """<b> About this program </b> 
                    <p>Copyright  2012 Maugin Guillaume. 
                    All rights reserved in accordance with
                    GPL v2 or later 
                    <p>This application can be used for
                    displaying OS and platform details.
                    <p>Python %s - PySide version %s - Qt version %s on %s""" )
     
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
     
            self._mode = self._getMode()
            #Init of the property for mode
            mode = property(self._getMode,self._setMode)
     
            #Get of the mode        self._mode = image.mode
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
     
        def _getMode(self):
            return self._mode
        def _setMode(self,_newMode):
            self._mode= _newMode
            self.update()
     
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self._mode =="select":
                #__ private variable 
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
     
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  18. #18
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    Ligne 66 remplace _setMode directement par une attribution de valeur à mode.

    Ligne 105 enlève les self. (property fonctionne directement au niveau de la classe).

  19. #19
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    102
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 102
    Par défaut Erreur property et prob tracé
    Citation Envoyé par ashren Voir le message
    Ligne 105 enlève les self. (property fonctionne directement au niveau de la classe).
    Si je fais cela j'ai une erreur,
    mode = property(_getMode,_setMode)
    NameError: global name '_getMode' is not defined


    Et j'ai pas l'impression qu'il me trace bien le trait quand je veux aussi :s

    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
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
            statusbar = QStatusBar(self)
            self.setStatusBar(statusbar)
            
            
            """
            Adding of actions for the tool bar
            """
            iconToolBar = self.addToolBar("iconBar")
            
            #About 
            _actionAbout = QAction(self)
            _actionAbout.triggered.connect(self._actionAbout)
              
            _actionAbout.setIcon(QIcon("Pics\info-icon.jpg"))
            _actionAbout.setStatusTip("Pop up the About dialog.")
            iconToolBar.addAction(_actionAbout)
            #Rubber
            _actionRubber = QAction(self)
            
            _actionRubber.setIcon(QIcon("Pics\eraser2.png"))
            _actionRubber.setStatusTip("Enable or Disable eraser tool")
            iconToolBar.addAction(_actionRubber)
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            #Check Box rub
            self._ckbox = QCheckBox("Rubber On")
            statusbar.addWidget(self._ckbox)
            if self._ckbox.isChecked():
                self._mode = "rub"
            else :
                self._mode = "select"
            #Init of the boolean to know whether we select or rub
            self.image._setMode("rub")
            
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
            
        def _actionAbout(self):
            '''Popup a box with about message.'''
            QMessageBox.about(self, "About PySide, Platform and the like",
            """<b> About this program </b> 
                    <p>Copyright  2012 Maugin Guillaume. 
                    All rights reserved in accordance with
                    GPL v2 or later 
                    <p>This application can be used for
                    displaying OS and platform details.
                    <p>Python %s - PySide version %s - Qt version %s on %s""" )
          
    class ImageView(QWidget):
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
            
            self._mode ="rub" 
            #self._getMode()
            #Init of the property for mode
            mode = property(self._getMode,self._setMode)
            
            #Get of the mode        self._mode = image.mode
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
            
        def _getMode(self):
            return self._mode
        def _setMode(self,_newMode):
            self._mode= _newMode
            self.update()
            
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self._mode =="select":
                #__ private variable 
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
                    
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            if self._mode =="select":
                print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
                    
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
            
            # Important ou non ?
           painter.drawLine(self.x1,self.y1,self.x2,self.y2)
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

  20. #20
    Membre expérimenté Avatar de ashren
    Homme Profil pro
    Inscrit en
    Mai 2012
    Messages
    101
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Mai 2012
    Messages : 101
    Par défaut
    La property devait être définie à la fin de la classe et non dans le __init__.

    J'ai modifié légèrement ton code (regarder les changements avec un diff viewer quelconque) :

    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
     
    from PySide.QtGui import *
    from PySide.QtCore import *
     
    class MainWindow(QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.image = ImageView(QImage())
            self.resize(500, 300)
            self.setWindowTitle("Image loader")
            statusbar = QStatusBar(self)
            self.setStatusBar(statusbar)
     
     
            """
            Adding of actions for the tool bar
            """
            iconToolBar = self.addToolBar("iconBar")
     
            #About 
            _actionAbout = QAction(self)
            _actionAbout.triggered.connect(self._actionAbout)
     
            _actionAbout.setIcon(QIcon("Pics\info-icon.jpg"))
            _actionAbout.setStatusTip("Pop up the About dialog.")
            iconToolBar.addAction(_actionAbout)
            #Rubber
            _actionRubber = QAction(self)
     
            _actionRubber.setIcon(QIcon("Pics\eraser2.png"))
            _actionRubber.setStatusTip("Enable or Disable eraser tool")
            iconToolBar.addAction(_actionRubber)
            """
            Add of scroll bars to see properly the images
            """
            self.area = QScrollArea(self)
            self.area.setWidget(self.image)
            self.area.setWidgetResizable(True)
            self.setCentralWidget(self.area)
            """
                Add of the Menu which contains all the features like of Open/Save/..
                and the edit options
            """
            menu = QMenuBar()
            self.setMenuBar(menu)
            _file = menu.addMenu('File')
            _edit = menu.addMenu("Edit")
            # Menu Open
            _action = QAction('Open', _file,shortcut=QKeySequence.Open)
            _action.triggered.connect(self.__actionOpen)
            _file.addAction(_action)
            # Menu Save
            _action = QAction('Save', _file,shortcut=QKeySequence.Save)
            _action.triggered.connect(self.__actionSave)
            _file.addAction(_action)
            # Menu Close
            _action = QAction('Close', _file,shortcut=QKeySequence.Close)
            _action.triggered.connect(self.__actionClose)
            _file.addAction(_action)
            #Menu Edit
            #Check Box rub
            self._ckbox = QCheckBox("Rubber On")
            statusbar.addWidget(self._ckbox)
            if self._ckbox.isChecked():
                self._mode = "rub"
            else :
                self._mode = "select"
            #Init of the boolean to know whether we select or rub
            self.image.mode = self._mode
            self._ckbox.stateChanged.connect(self.__rubberBoxChanged)
     
        def __rubberBoxChanged(self, state):
            if self._ckbox.isChecked():
                self._mode = 'rub'
            else:
                self._mode = 'select'
            self.image.mode = self._mode
     
        def __actionOpen(self):
            _file = QFileDialog.getOpenFileName(self, "Open Image", "", "Image Files (*.png *.jpg *.bmp)")
            if _file:
                self.image.setWorkingImage(QImage(_file[0]))
            else:
                print "Invalid Image"
     
        def __actionSave(self):
            _file = QFileDialog.getSaveFileName(parent=None, caption="Save image as")
            _result = self.image.workingImage().save(_file[0], "BMP", -1)
            # Test to know if it's working
            if _result:
                print "Saved successfully"
            else :
                print "Saving failed"
     
        def __actionClose(self):
            self.close()
     
        def _actionAbout(self):
            '''Popup a box with about message.'''
            QMessageBox.about(self, "About PySide, Platform and the like",
            """<b> About this program </b> 
                    <p>Copyright  2012 Maugin Guillaume. 
                    All rights reserved in accordance with
                    GPL v2 or later 
                    <p>This application can be used for
                    displaying OS and platform details.
                    <p>Python %s - PySide version %s - Qt version %s on %s""" )
     
    class ImageView(QWidget):       
        def __init__(self, image, parent=None):
            super(ImageView, self).__init__(parent=parent)
            self.__image = image
     
            self._mode ="rub" 
            #self._getMode()
     
            #Get of the mode        self._mode = image.mode
            #Init of selection 
            self.__band = QRubberBand(QRubberBand.Rectangle, self)
            self.__origin = None
            #Init of rubber
            #the rub is a rectangle that should be the size of one pixel and the color and full
            # of the one selected
     
        def getMode(self):
            return self._mode
        def setMode(self,_newMode):
            self._mode= _newMode
            self.update()
     
        def setWorkingImage(self, img):
            self.__image = img
            self.setMinimumSize(img.size())
            self.update()
     
        def workingImage(self):
            return self.__image
     
        def mousePressEvent(self, e):
            self.__origin = e.pos()
            if self._mode =="select":
                #__ private variable 
                self.__band.setGeometry(QRect(self.__origin, QSize()))
                self.__band.show()
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x1 = e.x()
                    self.y1 = e.y()
     
        def mouseReleaseEvent(self, e):
            self.__band.hide()
            if self._mode =="select":
                print "La selection est :", QRect.intersect(self.__band.geometry(), self.rect())
            if self._mode =="rub":
                if e.button() == Qt.LeftButton : 
                    self.x2 = e.x()
                    self.y2 = e.y()
                    painter = QPainter(self.__image)
                    painter.drawLine(self.x1,self.y1,self.x2,self.y2)
                    self.update()
     
        def mouseMoveEvent(self, e):
            self.__band.setGeometry(QRect(self.__origin, e.pos()).normalized())
            if self._mode == "rub":
                self.x2 = e.x()
                self.y2 = e.y()
                self.update()
     
        def paintEvent(self, e):
            painter = QPainter(self)
            painter.drawImage(self.rect(), self.__image)
     
            # Important ou non ?
            try:
                painter.drawLine(self.x1,self.y1,self.x2,self.y2)
            except:
                pass
     
        #Init of the property for mode
        mode = property(getMode, setMode)
     
    if __name__ == '__main__':
        app = QApplication([])
        win = MainWindow()
        win.show()
        app.exec_()

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 6 12345 ... DernièreDernière

Discussions similaires

  1. création d'un objet QImage
    Par Watier_53 dans le forum Qt
    Réponses: 14
    Dernier message: 01/01/2008, 19h12
  2. Problème avec QImage et QPainter
    Par Watier_53 dans le forum Qt
    Réponses: 5
    Dernier message: 19/12/2007, 10h42
  3. Question et boule de gomme
    Par said0011 dans le forum Débuter
    Réponses: 1
    Dernier message: 06/11/2007, 19h13
  4. [ActionListener] mystère et boule de gomme
    Par jcodeunpeu dans le forum AWT/Swing
    Réponses: 4
    Dernier message: 23/12/2005, 22h09
  5. [PyQt] QImage
    Par Jbx 2.0b dans le forum PyQt
    Réponses: 1
    Dernier message: 01/02/2005, 23h06

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