I’m writing a text editor in C++ (Qt Creator 14.0.1). I have managed to add line numbering and line highlighting from examples on internet.
If you start writing from top to bottom line numbering works fine. But if you open a file and put the text into the editor or paste bunch of text into it it will skip numbering multiple lines. here is my code and screenshot:
void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), Qt::lightGray);
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = static_cast<int>(blockBoundingGeometry(block).translated(contentOffset()).top());
int bottom = top + static_cast<int>(blockBoundingRect(block).height());
// Get the current line number
int currentLineNumber = textCursor().blockNumber();
// Loop through each block and draw line numbers
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString number = QString::number(blockNumber + 1);
// Check if this is the current line
if (blockNumber == currentLineNumber) {
// Set bold font for the current line number
QFont boldFont = painter.font();
boldFont.setBold(true);
painter.setFont(boldFont);
painter.setPen(Qt::blue); // Optional: change color for current line number
} else {
// Use normal font for other line numbers
painter.setFont(QFont());
painter.setPen(Qt::black);
}
// Adjust the x position to keep numbers left-aligned
painter.drawText(-5, top, lineNumberArea->width(), fontMetrics().height(),
Qt::AlignRight | Qt::AlignVCenter, number);
}
block = block.next();
top = bottom;
bottom = top + static_cast<int>(blockBoundingRect(block).height());
++blockNumber;
}
}
screenshot
I tried chatgpt and manipulating the algorithm to no avail.
Remisa Yousefvand is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.