当前位置:网站首页>Pyqt5 enables the qplaintextedit control to support line number display
Pyqt5 enables the qplaintextedit control to support line number display
2022-06-11 16:10:00 【Anti virus Alchemist】
I will develop a tool recently , The tool contains text box controls , For input PL/SQL Code block . If there is a problem with the code , The line number in question will be prompted . however QPlainTextEdit or QTextEdit Line number display is not supported , I haven't found any other supported controls . By consulting technical data , I encapsulated such a control , The effect is as follows :
Concrete realization
Don't bullshit , Go straight to the code
# coding: utf-8
# @FileName: textPlainWithLineNum.py
from PyQt5.QtCore import Qt, QRect, QSize, QPoint
from PyQt5.QtWidgets import QWidget, QTextEdit, QPlainTextEdit
from PyQt5.QtGui import QColor, QPainter, QTextFormat, QKeyEvent, QWheelEvent, QMouseEvent, QTextCursor
class QPlainTextEditWithLineNum(QPlainTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setLineWrapMode(QPlainTextEdit.NoWrap) # Don't wrap
self.lineNumberArea = LineNumPaint(self)
self.document().blockCountChanged.connect(self.update_line_num_width)
self.document().cursorPositionChanged.connect(self.highlightCurrentLine) # Highlight current line
self.verticalScrollBar().sliderMoved.connect(self.scroll_event) # The scroll bar moves to update the line number
self.update_line_num_width()
def wheelEvent(self, d: QWheelEvent) -> None:
self.scroll_event(d)
super().wheelEvent(d)
def scroll_event(self, event: QWheelEvent=None):
self.lineNumberArea.update()
def keyPressEvent(self, e: QKeyEvent) -> None:
super().keyPressEvent(e)
self.lineNumberArea.update()
def mousePressEvent(self, e: 'QMouseEvent') -> None:
super().mousePressEvent(e)
self.update()
self.highlightCurrentLine()
def lineNumberAreaWidth(self):
block_count = self.document().blockCount()
max_value = max(1, block_count)
d_count = len(str(max_value))
_width = self.fontMetrics().width('9') * d_count + 5
return _width
def update_line_num_width(self):
self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)
def resizeEvent(self, event):
super().resizeEvent(event)
cr = self.contentsRect()
self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))
def highlightCurrentLine(self):
extraSelections = []
if not self.isReadOnly():
selection = QTextEdit.ExtraSelection()
lineColor = QColor(Qt.blue).lighter(190)
selection.format.setBackground(lineColor)
selection.format.setProperty(QTextFormat.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
extraSelections.append(selection)
self.setExtraSelections(extraSelections)
def lineNumberAreaPaintEvent(self, event):
cursor = QTextCursor(self.document())
painter = QPainter(self.lineNumberArea)
painter.fillRect(event.rect(), Qt.lightGray)
line_height = self.fontMetrics().lineSpacing() # Row height with row spacing
block_number = self.cursorForPosition(QPoint(0, int(line_height / 2))).blockNumber()
first_visible_block = self.document().findBlock(block_number)
blockNumber = block_number
cursor.setPosition(self.cursorForPosition(QPoint(0, int(line_height / 2))).position())
rect = self.cursorRect()
scroll_compensation = rect.y() - int(rect.y() / line_height) * line_height
top = scroll_compensation
last_block_number = self.cursorForPosition(QPoint(0, self.height() - 1)).blockNumber()
height = self.fontMetrics().height()
block = first_visible_block
while block.isValid() and (top <= event.rect().bottom()) and blockNumber <= last_block_number:
# cur_line_count = block.lineCount()
if block.isVisible():
number = str(blockNumber + 1)
painter.setPen(Qt.black)
# print((0, top, self.lineNumberArea.width(), height), number)
painter.drawText(0, top, self.lineNumberArea.width(), height, Qt.AlignCenter, number)
block = block.next()
top = top + line_height
blockNumber += 1
class LineNumPaint(QWidget):
def __init__(self, q_edit):
super().__init__(q_edit)
self.q_edit_line_num = q_edit
def sizeHint(self):
return QSize(self.q_edit.lineNumberAreaWidth(), 0)
def paintEvent(self, event):
self.q_edit_line_num.lineNumberAreaPaintEvent(event)
Usage mode
import sys
from PyQt5.QtWidgets import QApplication
from textPlainWithLineNum import QPlainTextEditWithLineNum
app = QApplication(sys.argv)
codeEditor = QPlainTextEditWithLineNum()
codeEditor.setWindowTitle(" Editor with line number ")
codeEditor.setGeometry(100, 100, 800, 600)
codeEditor.show()
sys.exit(app.exec_())
If you want to use this control as another Dialog Child controls , Just pass in the instance of the parent control as a parameter , for example
self.plainTextEdit_plsql = QPlainTextEditWithLineNum(Dialog)
Last , I hope that in the future QT In the version , The text box can natively support line number display ~
边栏推荐
- 09-最小生成树 公路村村通
- Using cloud DB to build app quick start -server
- 书籍《阅读的方法》读后感
- GO语言数组和切片的区别
- WGet command use
- JDBC debugging error, ask for guidance
- Overview and operation of database dense equivalent query
- Db4ai: database driven AI
- Nat Common | le Modèle linguistique peut apprendre des distributions moléculaires complexes
- [Yugong series] June 2022 Net architecture class 079 cluster principle of distributed middleware schedulemaster
猜你喜欢

JDBC debugging error, ask for guidance

Take you in-depth understanding of AGC cloud database

Data enhancement
![[Yugong series] June 2022 Net architecture class 076- execution principle of distributed middleware schedulemaster](/img/c4/65babf7f51eaf1445ad6a02330975e.png)
[Yugong series] June 2022 Net architecture class 076- execution principle of distributed middleware schedulemaster

大龄码农从北京到荷兰的躺平生活

面试高频算法题---最长回文子串

书籍《阅读的方法》读后感

Collection | can explain the development and common methods of machine learning!

基于FPGA的VGA协议实现

AI tool for cutting-edge technology exploration: analog detection
随机推荐
How to predict SQL statement query time?
Elk enterprise log analysis system
Take you in-depth understanding of AGC cloud database
GO语言-Slice切片
Data enhancement
Toolbar details of user interface - autorunner automated test tool
完整的测试流程【杭州多测师】【杭州多测师_王sir】
[golang] leetcode special training - array and slice
From digital twinning to digital immortality, the "three-stage theory" of the development of the meta universe
Laravel8 implementation of sign in function
postgresql创建表
收藏 | 可解释机器学习发展和常见方法!
Tianjin Port coke wharf hand in hand map flapping software to visually unlock the smart coke port
Collection | can explain the development and common methods of machine learning!
Golang map basic operations
Deep separable convolution
Opengauss AI capability upgrade to create a new AI native database
Memory optimization table mot management
电脑下面的任务栏怎么显示打开的程序
Connect to the database using GSQL