Important: Please read the Qt Code of Conduct -

Please I need help with QTextBlock::isVisible in QTextEdit

  • I am writing a simple editor with a line number panel
    I want to get the first visible block using this snipet in a slot that is connect to update when the text change and blockCount changed
    @int total_line=this->TextEditor->document()->blockCount();
    int line_ctr=0;

    but no matter how first_visible_line is always 1 so block.isVisible() return always true .

    I want to keep QTextEdit because I will be adding syntaxe coloring using QSyntaxHil..
    Otherwise there is QPlainTextEdit::firstVisibleBlock() but I am not sure if QSyntaxHilighter can work on QPlainTextEdit

    Please need help.
    Thanks in advance

  • Seems that other people have experienced the "same issue":

    Btw I think you can simplify your code using something like this:

    @int getFirstVisibleBlock()
    QTextDocument *pDoc = TextEditor->document();
    int nFirstVisible = 0;
    for(QTextBlock block=pDoc->begin(); block!= pDoc->end(); block =
    nFirstVisible += 1;
    if (block.isVisible())
    return nFirstVisible;
    return nFirstVisible;

    Of course this will not solve an issue with isVisible() for blocks in QTextEdit if such exists :(

  • thanks I could not figure it out . but Ifound that QplainTextEdit support QsyntaxHilither so I went that way . It is working fine . my code is even simpler. Yes indeed i saw that thread yesterday when searching . thks

  • Actually, "isVisible" won't work for QTextEdit, but I managed to implement line numbers display for QTextEdit:

    Here is the tricky part:

    int QTextEditHighlighter::getFirstVisibleBlockId()
    // Detect the first block for which bounding rect - once
    // translated in absolute coordinates - is contained
    // by the editor's text area

    // Costly way of doing but since 
    // "blockBoundingGeometry(...)" doesn't exist 
    // for "QTextEdit"...
    QTextCursor curs = QTextCursor(this->document());
    for(int i=0; i < this->document()->blockCount(); ++i)
        QTextBlock block = curs.block();
        QRect r1 = this->viewport()->geometry();
        QRect r2 = this->document()->documentLayout()->blockBoundingRect(block).translated(
                    this->viewport()->geometry().x(), this->viewport()->geometry().y() - (
                        ) ).toRect();
        if (r1.contains(r2, true)) { return i; }
    return 0;


    See full implementation here:

    Hope it helps...

Log in to reply