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 :

Problème avec QScintilla


Sujet :

PyQt Python

  1. #1
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut Problème avec QScintilla
    Bonjour
    j'essaie de fabriquer un lexer perso. en surclassant Qsci.QsciLexerCustom. Pour commencer je voudrais juste mettre en rouge toutes les lignes qui commencent par un dièse.

    Je suis arrivé au code ci-dessous mais il me met tout en bleu (c'est déjà un premier pas).

    Quelqu'un voit-il le souci ?

    Toute info. est la bienvenue.

    Le code de MiniQsciScintilla_PersoViaEric.py
    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
    # -*- coding: utf-8 -*-
    #!/usr/bin/env python
     
    import sys
    from PyQt4 import QtCore, QtGui, Qsci
    from window_LecteurCodePython_HTML import Ui_window_LecteurCodePython_HTML
     
    ID_DEFAULT = 0
    ID_COMMENT = 1
     
    class myLexer(Qsci.QsciLexerCustom):
    # Struggle for a lexer.
        def description(self, style):
    # WARNING ! This method must be re-implemented by a sub-class.
            if style == 0:
                return 'ID_DEFAULT'
            if style == 1:
                return 'ID_COMMENT'
            return ''
     
        def defaultColor(self, style):
            if style==ID_DEFAULT:
                return QtGui.QColor(0,0,255)
            if style==ID_COMMENT: 
                return QtGui.QColor(255,0,0)
            return QtGui.QColor(0,0,0)
     
        def styleText(self, start, end):
    # Taken from the source code of Eric.
            self.editor.startStyling(start)
            if self.editor.text()[0] == '#':
                self.editor.setStyling(end, ID_COMMENT)
                self.editor.startStyling(start+end)
            else:
                self.editor.setStyling(end+1, ID_DEFAULT)
     
     
    class window_LecteurCodePython_HTML(QtGui.QMainWindow, Ui_window_LecteurCodePython_HTML):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            Ui_window_LecteurCodePython_HTML.__init__(self)
            self.setupUi(self)
     
            font = QtGui.QFont()
            font = QtGui.QFont()
            font.setFamily("Arial")
            font.setFixedPitch(True)
            font.setPointSize(10)
            fm = QtGui.QFontMetrics(font)
     
            self.textScintilla_Principal.setFont(font)
            self.textScintilla_Principal.setMarginsFont(font)
            self.textScintilla_Principal.setMarginLineNumbers(1,True)
            self.textScintilla_Principal.setMarginWidth(1, fm.width( "00000" ) + 5)
     
            self.textScintilla_Principal.setFolding(Qsci.QsciScintilla.BoxedTreeFoldStyle)
            self.textScintilla_Principal.setWrapMode(Qsci.QsciScintilla.WrapMode(Qsci.QsciScintillaBase.SC_WRAP_WORD))
            self.textScintilla_Principal.setWrapVisualFlags(Qsci.QsciScintilla.WrapVisualFlag(Qsci.QsciScintilla.WrapFlagByBorder), Qsci.QsciScintilla.WrapVisualFlag(Qsci.QsciScintilla.WrapFlagNone), 0)  
     
            self.textScintilla_Principal.setLexer(myLexer())
            textFichier= """# A red line
    /* This must
    be
    a fold */
           
    Nothing special for the moment  except that blue word."""
            self.textScintilla_Principal.setText(textFichier)
     
    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        LecteurCodePython = window_LecteurCodePython_HTML()
        LecteurCodePython.show()
        sys.exit(app.exec_())
    Voici le code complet de window_LecteurCodePython_HTML.py
    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
    # -*- coding: utf-8 -*-
     
    from PyQt4 import QtCore, QtGui
     
    class Ui_window_LecteurCodePython_HTML(object):
        def setupUi(self, window_LecteurCodePython_HTML):
            window_LecteurCodePython_HTML.setObjectName("window_LecteurCodePython_HTML")
            window_LecteurCodePython_HTML.resize(516, 397)
            self.centralwidget = QtGui.QWidget(window_LecteurCodePython_HTML)
            self.centralwidget.setObjectName("centralwidget")
            self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
            self.verticalLayout.setObjectName("verticalLayout")
            self.textScintilla_Principal = Qsci.QsciScintilla(self.centralwidget)
            self.textScintilla_Principal.setObjectName("textScintilla_Principal")
            self.verticalLayout.addWidget(self.textScintilla_Principal)
            window_LecteurCodePython_HTML.setCentralWidget(self.centralwidget)
            self.menubar = QtGui.QMenuBar(window_LecteurCodePython_HTML)
            self.menubar.setGeometry(QtCore.QRect(0, 0, 516, 21))
            self.menubar.setObjectName("menubar")
            self.menuFichier = QtGui.QMenu(self.menubar)
            self.menuFichier.setObjectName("menuFichier")
            window_LecteurCodePython_HTML.setMenuBar(self.menubar)
            self.statusbar = QtGui.QStatusBar(window_LecteurCodePython_HTML)
            self.statusbar.setObjectName("statusbar")
            window_LecteurCodePython_HTML.setStatusBar(self.statusbar)
            self.actionOuvrir = QtGui.QAction(window_LecteurCodePython_HTML)
            self.actionOuvrir.setObjectName("actionOuvrir")
            self.actionEnregistrer = QtGui.QAction(window_LecteurCodePython_HTML)
            self.actionEnregistrer.setObjectName("actionEnregistrer")
            self.actionExporterHTML = QtGui.QAction(window_LecteurCodePython_HTML)
            self.actionExporterHTML.setObjectName("actionExporterHTML")
            self.menuFichier.addAction(self.actionOuvrir)
            self.menuFichier.addAction(self.actionEnregistrer)
            self.menuFichier.addSeparator()
            self.menuFichier.addAction(self.actionExporterHTML)
            self.menubar.addAction(self.menuFichier.menuAction())
     
            self.retranslateUi(window_LecteurCodePython_HTML)
            QtCore.QMetaObject.connectSlotsByName(window_LecteurCodePython_HTML)
     
        def retranslateUi(self, window_LecteurCodePython_HTML):
            window_LecteurCodePython_HTML.setWindowTitle(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
            self.menuFichier.setTitle(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Actions", None, QtGui.QApplication.UnicodeUTF8))
            self.actionOuvrir.setText(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Ouvrir", None, QtGui.QApplication.UnicodeUTF8))
            self.actionOuvrir.setShortcut(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Ctrl+O", None, QtGui.QApplication.UnicodeUTF8))
            self.actionEnregistrer.setText(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Rechercher", None, QtGui.QApplication.UnicodeUTF8))
            self.actionEnregistrer.setShortcut(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Ctrl+S", None, QtGui.QApplication.UnicodeUTF8))
            self.actionExporterHTML.setText(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Exporter", None, QtGui.QApplication.UnicodeUTF8))
            self.actionExporterHTML.setShortcut(QtGui.QApplication.translate("window_LecteurCodePython_HTML", "Ctrl+E", None, QtGui.QApplication.UnicodeUTF8))
     
    from PyQt4 import Qsci
     
    if __name__ == "__main__":
        import sys
        app = QtGui.QApplication(sys.argv)
        window_LecteurCodePython_HTML = QtGui.QMainWindow()
        ui = Ui_window_LecteurCodePython_HTML()
        ui.setupUi(window_LecteurCodePython_HTML)
        window_LecteurCodePython_HTML.show()
        sys.exit(app.exec_())

  2. #2
    Membre chevronné

    Profil pro
    Account Manager
    Inscrit en
    Décembre 2006
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Localisation : France, Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Account Manager

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 301
    Points : 1 752
    Points
    1 752
    Par défaut
    Finalement,
    j'étais complétement à côté de la plaque. Un grand manitou de la liste PyQt m'a donné la solution non évidente suivante :
    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
    #!/usr/bin/env python
    #coding=utf-8
    import sys
    from PyQt4 import QtCore, QtGui, Qsci
     
     
    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            self.setWindowTitle('Custom Lexer Example')
            self.setGeometry(QtCore.QRect(50,200,400,400))
            self.editor = Qsci.QsciScintilla(self)
            self.editor.setUtf8(True)
            self.editor.setMarginWidth(2, 15)
            self.editor.setFolding(True)
            self.setCentralWidget(self.editor)
            self.lexer = CustomLexer(self.editor)
            self.editor.setLexer(self.lexer)
            self.editor.setText('\n# sample source\n\nfoo = 1\nbar = 2\n')
     
     
    class CustomLexer(Qsci.QsciLexerCustom):
        def __init__(self, parent):
            Qsci.QsciLexerCustom.__init__(self, parent)
            self._styles = {
                0: 'Default',
                1: 'Comment',
                2: 'Key',
                3: 'Assignment',
                4: 'Value',
                }
            for key,value in self._styles.iteritems():
                setattr(self, value, key)
     
        def description(self, style):
            return self._styles.get(style, '')
     
        def defaultColor(self, style):
            if style == self.Default:
                return QtGui.QColor('#000000')
            elif style == self.Comment:
                return QtGui.QColor('#C0C0C0')
            elif style == self.Key:
                return QtGui.QColor('#0000CC')
            elif style == self.Assignment:
                return QtGui.QColor('#CC0000')
            elif style == self.Value:
                return QtGui.QColor('#00CC00')
            return Qsci.QsciLexerCustom.defaultColor(self, style)
     
        def styleText(self, start, end):
            editor = self.editor()
            if editor is None:
                return
     
            # scintilla works with encoded bytes, not decoded characters.
            # this matters if the source contains non-ascii characters and
            # a multi-byte encoding is used (e.g. utf-8)
            source = ''
            if end > editor.length():
                end = editor.length()
            if end > start:
                if sys.hexversion >= 0x02060000:
                    # faster when styling big files, but needs python 2.6
                    source = bytearray(end - start)
                    editor.SendScintilla(
                        editor.SCI_GETTEXTRANGE, start, end, source)
                else:
                    source = unicode(editor.text()
                                    ).encode('utf-8')[start:end]
            if not source:
                return
     
            # the line index will also be needed to implement folding
            index = editor.SendScintilla(editor.SCI_LINEFROMPOSITION, start)
            if index > 0:
                # the previous state may be needed for multi-line styling
                pos = editor.SendScintilla(editor.SCI_GETLINEENDPOSITION,
                                           index - 1)
                state = editor.SendScintilla(editor.SCI_GETSTYLEAT, pos)
            else:
                state = self.Default
     
            set_style = self.setStyling
            self.startStyling(start, 0x1f)
     
            # scintilla always asks to style whole lines
            for line in source.splitlines(True):
                length = len(line)
                if line.startswith('+ '):
                    index+=1
                    state = self.Comment
                else:
                    # the following will style lines like "x = 0"
                    pos = line.find('=')
                    if pos > 0:
                        set_style(pos, self.Key)
                        set_style(1, self.Assignment)
                        length = length - pos - 1
                        state = self.Value
                    else:
                        state = self.Default
                set_style(length, state)
                # folding implementation goes here
                editor.SendScintilla(editor.SCI_SETFOLDLEVEL, 1)
                index += 1
     
     
    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        app.connect(app, QtCore.SIGNAL('lastWindowClosed()'),
                    QtCore.SLOT('quit()'))
        win = MainWindow()
        win.show()
        sys.exit(app.exec_())

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. VC++ Direct3D8, problème avec LPD3DXFONT et LPD3DTEXTURE8
    Par Magus (Dave) dans le forum DirectX
    Réponses: 3
    Dernier message: 03/08/2002, 11h10
  2. Problème avec [b]struct[/b]
    Par Bouziane Abderraouf dans le forum CORBA
    Réponses: 2
    Dernier message: 17/07/2002, 10h25
  3. Problème avec le type 'Corba::Any_out'
    Par Steven dans le forum CORBA
    Réponses: 2
    Dernier message: 14/07/2002, 18h48
  4. Problème avec la mémoire virtuelle
    Par Anonymous dans le forum CORBA
    Réponses: 13
    Dernier message: 16/04/2002, 16h10

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