- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经编写了一个小的 Python PyQt4 程序来语法高亮 QPlainTextEdit 字段中的 MySQL 源代码。以下代码用于正确地对 MySQL 文本进行颜色编码。
如果有人编辑明文字段,我如何自动更新文本颜色?感谢您提供任何帮助或建议。
import sys, time
from PyQt4 import QtCore, QtGui
import syntax
class MyApp(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 410, 220)
self.setWindowTitle('MySQL Source Color Coding')
self.layout = QtGui.QVBoxLayout(self)
self.plaintext = QtGui.QPlainTextEdit()
self.plaintext.setFont(QtGui.QFont ("Consolas", 9))
self.plaintext.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
x = syntax.PythonHighlighter(self.plaintext.document())
self.layout.addWidget(self.plaintext)
mysqlcode = """\
select dt as 'Date',
dayName as "Day",
count(create_date) as 'Transaction Count'
from calendar
left join transaction
on dt = date(create_date)
where dt <= NOW()
and dt >= '2015-07-21'
group by dt
order by dt desc;
"""
self.plaintext.setPlainText(mysqlcode)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
app.exec_()
语法.py
import sys
from PyQt4.QtCore import QRegExp
from PyQt4.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
def format(color, style=''):
"""Return a QTextCharFormat with the given attributes.
"""
_color = QColor()
_color.setNamedColor(color)
_format = QTextCharFormat()
_format.setForeground(_color)
if 'bold' in style:
_format.setFontWeight(QFont.Bold)
if 'italic' in style:
_format.setFontItalic(True)
return _format
# Syntax styles that can be shared by all languages
STYLES = {
'keyword': format('blue'),
'operator': format('darkred'),
'brace': format('black','bold'),
'defclass': format('black', 'bold'),
'string': format('darkGreen'),
'string2': format('darkMagenta'),
'comment': format('Grey', 'italic'),
'self': format('black', 'italic'),
'numbers': format('darkMagenta'),
}
class PythonHighlighter (QSyntaxHighlighter):
"""Syntax highlighter for the mysql language.
"""
# mysql keywords
keywords = [
"use", "select", "as", "then", "case", "end",
"from", "where", "group by", "order by", "desc", "asc",
"distinct", "on", "left join", "right join", "count",
"sum", "max", "min","distinct", "and", "in", "or",
"date","NOW", "like",
]
# Python operators
operators = [
"&&", "between", "binary", "&",
"\\^", "=", ">=", ">",
"is null", "null", "<=", "<",
" like ", "regexp", "not", ";",",",
]
# Python braces
braces = [
'\{', '\}', '\(', '\)', '\[', '\]',
]
def __init__(self, document):
QSyntaxHighlighter.__init__(self, document)
print "QSyntaxHighlighter"
# Multi-line strings (expression, flag, style)
# FIXME: The triple-quotes in these two lines will mess up the
# syntax highlighting from this point onward
self.tri_single = (QRegExp("'''"), 1, STYLES['string2'])
self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])
rules = []
# Keyword, operator, and brace rules
rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
for w in PythonHighlighter.keywords]
rules += [(r'%s' % o, 0, STYLES['operator'])
for o in PythonHighlighter.operators]
rules += [(r'%s' % b, 0, STYLES['brace'])
for b in PythonHighlighter.braces]
# All other rules
rules += [
# 'self'
(r'\bself\b', 0, STYLES['self']),
# Double-quoted string, possibly containing escape sequences
(r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
# Single-quoted string, possibly containing escape sequences
(r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
# 'def' followed by an identifier
(r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
# 'class' followed by an identifier
(r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
# From '#' until a newline
(r'#[^\n]*', 0, STYLES['comment']),
# Numeric literals
(r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']),
(r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
(r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b', 0, STYLES['numbers']),
]
# Build a QRegExp for each pattern
self.rules = [(QRegExp(pat), index, fmt)
for (pat, index, fmt) in rules]
def highlightBlock(self, text):
print "highlightBlock"
"""Apply syntax highlighting to the given block of text.
"""
# Do other syntax formatting
for expression, nth, format in self.rules:
index = expression.indexIn(text, 0)
while index >= 0:
# We actually want the index of the nth match
index = expression.pos(nth)
length = expression.cap(nth).length()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
# Do multi-line strings
in_multiline = self.match_multiline(text, *self.tri_single)
if not in_multiline:
in_multiline = self.match_multiline(text, *self.tri_double)
def match_multiline(self, text, delimiter, in_state, style):
"""Do highlighting of multi-line strings. ``delimiter`` should be a
``QRegExp`` for triple-single-quotes or triple-double-quotes, and
``in_state`` should be a unique integer to represent the corresponding
state changes when inside those strings. Returns True if we're still
inside a multi-line string when this function is finished.
"""
# If inside triple-single quotes, start at 0
if self.previousBlockState() == in_state:
start = 0
add = 0
# Otherwise, look for the delimiter on this line
else:
start = delimiter.indexIn(text)
# Move past this match
add = delimiter.matchedLength()
# As long as there's a delimiter match on this line...
while start >= 0:
# Look for the ending delimiter
end = delimiter.indexIn(text, start + add)
# Ending delimiter on this line?
if end >= add:
length = end - start + add + delimiter.matchedLength()
self.setCurrentBlockState(0)
# No; multi-line string
else:
self.setCurrentBlockState(in_state)
length = text.length() - start + add
# Apply formatting
self.setFormat(start, length, style)
# Look for the next match
start = delimiter.indexIn(text, start + length)
# Return True if still inside a multi-line string, False otherwise
if self.currentBlockState() == in_state:
return True
else:
return False
最佳答案
我在以下位置找到了一个很好的如何使用 QSyntaxHighlighter 的示例:
http://carsonfarmer.com/2009/07/syntax-highlighting-with-pyqt/
Carson Farmer 的 QSyntaxHighlighter 实现效果很好,并在用户修改文本字段时自动更新语法颜色编码。
'''
Python Syntax Highlighting Example
Copyright (C) 2009 Carson J. Q. Farmer
'''
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyHighlighter( QSyntaxHighlighter ):
def __init__( self, parent, theme ):
QSyntaxHighlighter.__init__( self, parent )
self.parent = parent
keyword = QTextCharFormat()
reservedClasses = QTextCharFormat()
assignmentOperator = QTextCharFormat()
delimiter = QTextCharFormat()
specialConstant = QTextCharFormat()
boolean = QTextCharFormat()
number = QTextCharFormat()
comment = QTextCharFormat()
string = QTextCharFormat()
singleQuotedString = QTextCharFormat()
self.highlightingRules = []
# keyword
brush = QBrush( Qt.darkBlue, Qt.SolidPattern )
keyword.setForeground( brush )
keyword.setFontWeight( QFont.Bold )
keywords = QStringList( [ "break", "else", "for", "if", "in",
"next", "repeat", "return", "switch",
"try", "while" ] )
for word in keywords:
pattern = QRegExp("\\b" + word + "\\b")
rule = HighlightingRule( pattern, keyword )
self.highlightingRules.append( rule )
# reservedClasses
reservedClasses.setForeground( brush )
reservedClasses.setFontWeight( QFont.Bold )
keywords = QStringList( [ "array", "character", "complex",
"data.frame", "double", "factor",
"function", "integer", "list",
"logical", "matrix", "numeric",
"vector" ] )
for word in keywords:
pattern = QRegExp("\\b" + word + "\\b")
rule = HighlightingRule( pattern, reservedClasses )
self.highlightingRules.append( rule )
# assignmentOperator
brush = QBrush( Qt.yellow, Qt.SolidPattern )
pattern = QRegExp( "(<){1,2}-" )
assignmentOperator.setForeground( brush )
assignmentOperator.setFontWeight( QFont.Bold )
rule = HighlightingRule( pattern, assignmentOperator )
self.highlightingRules.append( rule )
# delimiter
pattern = QRegExp( "[\)\(]+|[\{\}]+|[][]+" )
delimiter.setForeground( brush )
delimiter.setFontWeight( QFont.Bold )
rule = HighlightingRule( pattern, delimiter )
self.highlightingRules.append( rule )
# specialConstant
brush = QBrush( Qt.green, Qt.SolidPattern )
specialConstant.setForeground( brush )
keywords = QStringList( [ "Inf", "NA", "NaN", "NULL" ] )
for word in keywords:
pattern = QRegExp("\\b" + word + "\\b")
rule = HighlightingRule( pattern, specialConstant )
self.highlightingRules.append( rule )
# boolean
boolean.setForeground( brush )
keywords = QStringList( [ "TRUE", "FALSE" ] )
for word in keywords:
pattern = QRegExp("\\b" + word + "\\b")
rule = HighlightingRule( pattern, boolean )
self.highlightingRules.append( rule )
# number
pattern = QRegExp( "[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?" )
pattern.setMinimal( True )
number.setForeground( brush )
rule = HighlightingRule( pattern, number )
self.highlightingRules.append( rule )
# comment
brush = QBrush( Qt.blue, Qt.SolidPattern )
pattern = QRegExp( "#[^\n]*" )
comment.setForeground( brush )
rule = HighlightingRule( pattern, comment )
self.highlightingRules.append( rule )
# string
brush = QBrush( Qt.red, Qt.SolidPattern )
pattern = QRegExp( "\".*\"" )
pattern.setMinimal( True )
string.setForeground( brush )
rule = HighlightingRule( pattern, string )
self.highlightingRules.append( rule )
# singleQuotedString
pattern = QRegExp( "\'.*\'" )
pattern.setMinimal( True )
singleQuotedString.setForeground( brush )
rule = HighlightingRule( pattern, singleQuotedString )
self.highlightingRules.append( rule )
def highlightBlock( self, text ):
for rule in self.highlightingRules:
expression = QRegExp( rule.pattern )
index = expression.indexIn( text )
while index >= 0:
length = expression.matchedLength()
self.setFormat( index, length, rule.format )
index = text.indexOf( expression, index + length )
self.setCurrentBlockState( 0 )
class HighlightingRule():
def __init__( self, pattern, format ):
self.pattern = pattern
self.format = format
class TestApp( QMainWindow ):
def __init__(self):
QMainWindow.__init__(self)
font = QFont()
font.setFamily( "Courier" )
font.setFixedPitch( True )
font.setPointSize( 10 )
editor = QTextEdit()
editor.setFont( font )
highlighter = MyHighlighter( editor, "Classic" )
self.setCentralWidget( editor )
self.setWindowTitle( "Syntax Highlighter" )
if __name__ == "__main__":
app = QApplication( sys.argv )
window = TestApp()
window.show()
sys.exit( app.exec_() )
关于python - 如何在用户更改文本时更新 QSyntaxHighlighter 颜色编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26679515/
我查看了网站上的一些问题,但还没有完全弄清楚我做错了什么。我有一些这样的代码: var mongoose = require('mongoose'), db = mongoose.connect('m
基本上,根据 this bl.ocks,我试图在开始新序列之前让所有 block 都变为 0。我认为我需要的是以下顺序: 更新为0 退出到0 更新随机数 输入新号码 我尝试通过添加以下代码块来遵循上述
我试图通过使用随机数在循环中设置 JSlider 位置来模拟“赛马”的投注结果。我的问题是,当然,我无法在线程执行时更新 GUI,因此我的 JSlider 似乎没有在竞赛,它们从头到尾都在运行。我尝试
该功能非常简单: 变量:$table是正在更新的表$fields 是表中的字段,$values 从帖子生成并放入 $values 数组中而$where是表的索引字段的id值$indxfldnm 是索引
让我们想象一个环境:有一个数据库客户端和一个数据库服务器。数据库客户端可以是 Java 程序或其他程序等;数据库服务器可以是mysql、oracle等。 需求是在数据库服务器上的一个表中插入大量记录。
在我当前的应用程序中,我正在制作一个菜单结构,它可以递归地创建自己的子菜单。然而,由于这个原因,我发现很难也允许某种重新排序方法。大多数应用程序可能只是通过“排序”列进行排序,但是在这种情况下,尽管这
Provisioning Profile 有 key , key 链依赖于它。我想知道 key 什么时候会改变。 Key will change after renew Provisioning Pr
截至目前,我在\server\publications.js 中有我的 MongoDB“选择”,例如: Meteor.publish("jobLocations", function () { r
我读到 UI 应该始终在主线程上更新。但是,当谈到实现这些更新的首选方法时,我有点困惑。 我有各种函数可以执行一些条件检查,然后使用结果来确定如何更新 UI。我的问题是整个函数应该在主线程上运行吗?应
我在代理后面,我无法构建 Docker 镜像。 我试过 FROM ubuntu , FROM centos和 FROM alpine ,但是 apt-get update/yum update/apk
我构建了一个 Java 应用程序,它向外部授权客户端公开网络服务。 Web 服务使用带有证书身份验证的 WS-security。基本上我们充当自定义证书颁发机构 - 我们在我们的服务器上维护一个 ja
因此,我有时会在上传新版本时使用 app_offline.htm 使应用程序离线。 但是,当我上传较大的 dll 时,我收到黄色错误屏幕,指出无法加载 dll。 这似乎与我对 app_offline.
我刚刚下载了 VS Apache Cordova Tools Update 5,但遇到了 Node 和 NPM 的问题。我使用默认的空白 cordova 项目进行测试。 版本 如果我在 VS 项目中对
所以我有一个使用传单库实例化的 map 对象。 map 实例在单独的模板中创建并以这种方式路由:- var app = angular.module('myApp', ['ui', 'ngResour
我使用较早的 Java 6 u 3 获得的帧速率是新版本的两倍。很奇怪。谁能解释一下? 在 Core 2 Duo 1.83ghz 上,集成视频(仅使用一个内核)- 1500(较旧的 java)与 70
我正在使用 angular 1.2 ng-repeat 创建的 div 也包含 ng-click 点击时 ng-click 更新 $scope $scope 中的变化反射(reflect)在使用 $a
这些方法有什么区别 public final void moveCamera(CameraUpdate更新)和public final void animateCamera (CameraUpdate
我尝试了另一篇文章中某人评论中关于如何将树更改为列表的建议。但是,我在某处(或某物)有未声明的变量,所以我列表中的值是 [_G667, _G673, _G679],而不是 [5, 2, 6],这是正确
实现以下场景的最佳方法是什么? 我需要从java应用程序调用/查询包含数百万条记录的数据库表。然后,对于表中的每条记录,我的应用程序应该调用第三方 API 并获取状态字段作为响应。然后我的应用程序应该
只是在编写一些与 java 图形相关的代码,这是我今天的讲座中的非常简单的示例。不管怎样,互联网似乎说更新不会被系统触发器调用,例如调整框架大小等。在这个例子中,更新是由这样的触发器调用的(因此当我只
我是一名优秀的程序员,十分优秀!