QTextCursor cursor(textEdit->textCursor());cursor.movePosition(QTextCursor::Start);QTextCharFormat textFormat;QTextCharFormat blueFormat;blueFormat.setForeground(Qt::blue);QTextCharFormat redFormat;redFormat.setForeground(Qt::red);cursor.insertText("this is text ", textFormat);cursor.insertBlock();cursor.insertText("right", blueFormat);cursor.insertBlock();cursor.insertText(", but this is text ", textFormat);cursor.insertBlock();cursor.insertText("not right", redFormat);
C++ (Qt)...void Highlighter::highlightBlock(const QString &text){ BlockData *data = parseBlock(text); setFormat(data->rightStart, data->rightLen, rightFormat); setFormat(data->notRightStart, data->notRightLen, notRightFormat);} BockData* Highlighter::parseBlock(const QString &text){ BlockData *data = new BlockData; ... setCurrentBlockUserData(data); return data;}
C++ (Qt)void MyTextEdit::keyPressEvent(QEvent *e){ if (key pressed) { QTextCursor cur = textCursor(); int cur_pos = cur.positionInBlock(); BlockData *d = static_cast<BlockData*>(cur.block().userData()); if (d) { // [1] } } QTextEdit::keyPressEvent(e);}
C++ (Qt)void Highlighter::highlightBlock(const QString &text){ BlockData *data = parseBlock(text); // <----- ....}
C++ (Qt)void OmTextEdit::setMyText(QString text){ QTextCursor cursor(this->textCursor()); cursor.movePosition(QTextCursor::Start); cursor.insertText("this is text "); cursor.insertText("right"); // [1] cursor.insertText(", but this is text");} Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent){} void Highlighter::highlightBlock(const QString &text){ qDebug() << text; BlockData *data = parseBlock(text); //setFormat(data->rightStart, data->rightLen, rightFormat); //setFormat(data->notRightStart, data->notRightLen, notRightFormat);} BlockData* Highlighter::parseBlock(const QString &text){ BlockData *data = new BlockData; // [2] setCurrentBlockUserData(data); return data;}