Search code examples
qtqt4qt5

How to keep an editable QLabel inside paintEvent


I want to keep an ellipse and QLabel in horizontal layout inside paintEvent and want QLabel should be editable on double click.

void CascadeColorHighlightWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    m_contRect = contentsRect().adjusted(1, 1, -1, -1);
    painter.setPen(QPen(QColor(176, 176, 176),1));
    painter.setBrush(QColor(255,255,255));
    painter.drawRect(m_contRect);

    painter.setPen(QPen(QColor(51,51,51),1));
    QFont font( "Calibri" );
    font.setPixelSize(14);
    painter.setFont( font );

    painter.drawText(QPointF(m_contRect.x() + 18, m_contRect.y() + 28), "Color Highlight");

    int rectYPos = m_contRect.y() + 55;

    painter.setPen(Qt::NoPen);
    QRectF ellipseRect = QRectF(m_contRect.x() + 18, rectYPos, 16, 16);

    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(224,90,90));
    painter.drawEllipse(ellipseRect);

    QLabel dummy;
    dummy.setText("Density");
    dummy.setTextInteractionFlags(Qt::TextEditable);

    QStyleOptionFrameV2 panel;
    panel.initFrom(&dummy);
    panel.rect = QRect(m_contRect.x() + 54, m_contRect.y() + 48, 100, 30);  // QFontMetric could provide height.
    panel.lineWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &panel, &dummy);
    style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panel, &painter, this);

}

Solution

  • When user point focus to QLabel image, create new QLabel object, move to appropriate window position and set text. User will see "living" editor. When user focus out remove QLabel object and repaint your image with QLabel picture.