Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QLabel not being showed in QTextEdit



  • I wrote a class that inherits from QTextEdit and overrides the printEvent method in which I need to paint a label in the top right corner of a QRect painted in the document

    void TextEditor::paintEvent(QPaintEvent *e) {
    
        try {
            QPainter painter(viewport());
            QTextCursor cursor(document());
            painter.setPen(Qt::yellow);
            cursor.setPosition(1);
            QRect cRect = cursorRect(cursor);
            QLabel label = QLabel("test", this);
            label.setTextInteractionFlags(Qt::NoTextInteraction);
            label.setStyleSheet("QLabel { background-color : red; color : white; }");
            label.move(cRect.topRight());
            painter.drawRect(cRect);
                        
            document()->drawContents(&painter);
        } catch (const std::exception &e) {
            qDebug() << e.what();
        }
    }
    

    The QRect is correctly painted inside the document but the label is not.



  • @anphetamina
    I have no idea whether your principle is supposed to work or not, but if nothing else your QLabel label is a local variable which goes out of scope at the end of this method, so I think it would fail to draw on that account if nothing else.



  • You're right, so I've tried to follow the same approach as the cursor invoking drawRect also for the label, like this:

    QRect lRect = label.rect();
    painter.drawRect(lRect);
    

    But it prints a rectangle in the top-left corner of the document using the same color of the painter


  • Lifetime Qt Champion

    Hi,

    At no point you are rendering your label. You are just painting literally a rectangle based on a label that has no "physical presence" since it's not even shown.

    What exactly do you want to do with that QLabel ?


Log in to reply