Nominate our 2022 Qt Champions!

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());
            QRect cRect = cursorRect(cursor);
            QLabel label = QLabel("test", this);
            label.setStyleSheet("QLabel { background-color : red; color : white; }");
        } 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();

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

  • Lifetime Qt Champion


    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