1 from PyQt4 import QtCore, QtGui
2
3
4 class MainWindow(QtGui.QMainWindow):
5 def __init__(self, parent=None):
6 super(MainWindow, self).__init__(parent)
7
8 self.setupFileMenu()
9 self.setupHelpMenu()
10 self.setupEditor()
11
12 self.setCentralWidget(self.editor)
13 self.setWindowTitle("Syntax Highlighter")
14
15 def about(self):
16 QtGui.QMessageBox.about(self, "About Syntax Highlighter",
17 "<p>The <b>Syntax Highlighter</b> example shows how to " \
18 "perform simple syntax highlighting by subclassing the " \
19 "QSyntaxHighlighter class and describing highlighting " \
20 "rules using regular expressions.</p>")
21
22 def newFile(self):
23 self.editor.clear()
24
25 def openFile(self, path=None):
26 if not path:
27 path = QtGui.QFileDialog.getOpenFileName(self, "Open File",
28 '', "C++ Files (*.cpp *.h)")
29
30 if path:
31 inFile = QtCore.QFile(path)
32 if inFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
33 text = inFile.readAll()
34
35 try:
36 # Python v3.
37 text = str(text, encoding='ascii')
38 except TypeError:
39 # Python v2.
40 text = str(text)
41
42 self.editor.setPlainText(text)
43
44 def setupEditor(self):
45 font = QtGui.QFont()
46 font.setFamily('Courier')
47 font.setFixedPitch(True)
48 font.setPointSize(10)
49
50 self.editor = QtGui.QTextEdit()
51 self.editor.setFont(font)
52
53 self.highlighter = Highlighter(self.editor.document())
54
55 def setupFileMenu(self):
56 fileMenu = QtGui.QMenu("&File", self)
57 self.menuBar().addMenu(fileMenu)
58
59 fileMenu.addAction("&New...", self.newFile, "Ctrl+N")
60 fileMenu.addAction("&Open...", self.openFile, "Ctrl+O")
61 fileMenu.addAction("E&xit", QtGui.qApp.quit, "Ctrl+Q")
62
63 def setupHelpMenu(self):
64 helpMenu = QtGui.QMenu("&Help", self)
65 self.menuBar().addMenu(helpMenu)
66
67 helpMenu.addAction("&About", self.about)
68 helpMenu.addAction("About &Qt", QtGui.qApp.aboutQt)
69
70
71 class Highlighter(QtGui.QSyntaxHighlighter):
72 def __init__(self, parent=None):
73 super(Highlighter, self).__init__(parent)
74
75 keywordFormat = QtGui.QTextCharFormat()
76 keywordFormat.setForeground(QtCore.Qt.darkBlue)
77 keywordFormat.setFontWeight(QtGui.QFont.Bold)
78
79 keywordPatterns = ["\\bchar\\b", "\\bclass\\b", "\\bconst\\b",
80 "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b",
81 "\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b",
82 "\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b",
83 "\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b",
84 "\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b",
85 "\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b",
86 "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b",
87 "\\bvolatile\\b"]
88
89 self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat)
90 for pattern in keywordPatterns]
91
92 classFormat = QtGui.QTextCharFormat()
93 classFormat.setFontWeight(QtGui.QFont.Bold)
94 classFormat.setForeground(QtCore.Qt.darkMagenta)
95 self.highlightingRules.append((QtCore.QRegExp("\\bQ[A-Za-z]+\\b"),
96 classFormat))
97
98 singleLineCommentFormat = QtGui.QTextCharFormat()
99 singleLineCommentFormat.setForeground(QtCore.Qt.red)
100 self.highlightingRules.append((QtCore.QRegExp("//[^\n]*"),
101 singleLineCommentFormat))
102
103 self.multiLineCommentFormat = QtGui.QTextCharFormat()
104 self.multiLineCommentFormat.setForeground(QtCore.Qt.red)
105
106 quotationFormat = QtGui.QTextCharFormat()
107 quotationFormat.setForeground(QtCore.Qt.darkGreen)
108 self.highlightingRules.append((QtCore.QRegExp("\".*\""),
109 quotationFormat))
110
111 functionFormat = QtGui.QTextCharFormat()
112 functionFormat.setFontItalic(True)
113 functionFormat.setForeground(QtCore.Qt.blue)
114 self.highlightingRules.append((QtCore.QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
115 functionFormat))
116
117 self.commentStartExpression = QtCore.QRegExp("/\\*")
118 self.commentEndExpression = QtCore.QRegExp("\\*/")
119
120 def highlightBlock(self, text):
121 for pattern, format in self.highlightingRules:
122 expression = QtCore.QRegExp(pattern)
123 index = expression.indexIn(text)
124 while index >= 0:
125 length = expression.matchedLength()
126 self.setFormat(index, length, format)
127 index = expression.indexIn(text, index + length)
128
129 self.setCurrentBlockState(0)
130
131 startIndex = 0
132 if self.previousBlockState() != 1:
133 startIndex = self.commentStartExpression.indexIn(text)
134
135 while startIndex >= 0:
136 endIndex = self.commentEndExpression.indexIn(text, startIndex)
137
138 if endIndex == -1:
139 self.setCurrentBlockState(1)
140 commentLength = len(text) - startIndex
141 else:
142 commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()
143
144 self.setFormat(startIndex, commentLength,
145 self.multiLineCommentFormat)
146 startIndex = self.commentStartExpression.indexIn(text,
147 startIndex + commentLength);
148
149
150 if __name__ == '__main__':
151
152 import sys
153
154 app = QtGui.QApplication(sys.argv)
155 window = MainWindow()
156 window.resize(640, 512)
157 window.show()
158 sys.exit(app.exec_())

  

 posted on 2011-07-18 11:09  eth0  阅读(521)  评论(0编辑  收藏  举报